small medium large xlarge

Me_pragsmall
14 Jun 2014, 08:00
Paul Barry (4 posts)

Just a suggestion. Rather than introducing the private function, it is possible to default the value of “total” to 0, that way the sum function can be invoked without providing the starting value:

    def sum([], total \\ 0), do: total
    def sum([head|tail], total), do: sum(tail, head+total)

It is then possible to call it like this (note that we can seed the value of “total” to anything now):

    iex(3)> MyList.sum [2, 3, 4]
    9
    iex(4)> MyList.sum [2, 3, 4], 10
    19
    iex(5)> MyList.sum [2, 3, 4], -3
    6
    iex(7)> MyList.sum [2, 3, 4], -9 
    0

As I said, just a suggestion.

Generic-user-small
12 Nov 2015, 15:36
asymmetric . (4 posts)

Hi Paul,

Avdi Grimm had the same question, and it’s been answered by Dave here.

To sum it up, Dave thinks that the total parameter shouldn’t be part of sum’s API.

Here is my implementation anyway:

def sum(list, total \\ 0)
def sum([], total), do: total
def sum([ head | tail ], total), do: sum(tail, head + total)
You must be logged in to comment