Bercovici Adrian
Bercovici Adrian

Reputation: 9370

How do accumulators work in Haskell?

Hello i am trying to understand how do accumulators work by creating the following method :

It receives a number and it creates a tuple of: (sum [0..nr], [0..nr]). For instance, given 4, it should return (10, [0,1,2,3,4]).

This is the code I have:

accu :: Int -> (Int, [Int])
accu 0  = (0, [0])
accu nr = go (0, []) nr where   --I do not get this line, mainly the first argument
            go (s,ls) 0  = (s, 0:ls)
            go (s,ls) nr = go (s+nr, nr:ls) (nr-1)

I do not understand how the accumulator changes its value, since it is not a function, and thus shouldn't it be immutable? Shouldn't it be like a constant in my case?

Upvotes: 1

Views: 1873

Answers (2)

fp_mora
fp_mora

Reputation: 714

Why not do it simply.

(\n -> (sum [0..n], [0..n])) 4
(10,[0,1,2,3,4])

Or this is cleaner but longer.

(\n -> (\l -> (sum l, l)) [0..n]) 5
(15,[0,1,2,3,4,5])

Upvotes: 0

dvaergiller
dvaergiller

Reputation: 815

go is a function that is locally defined using the where keyword and then used directly in the accu function. Have a look here: http://learnyouahaskell.com/syntax-in-functions#where

That means the accumulator does not really change, it is just a different accumulator in each recursive call to the go function. The last line will recursively call the go function with a new accumulator value.

Upvotes: 3

Related Questions