Edy
Edy

Reputation: 5

Accumulator in Haskell

I have this function:

map(\x -> if (isLetter x) then (update exp (Literal x) "") else Epsilon) "a+b+c+" where exp = Epsilon

and i want for each step of the map function my variable exp to not be Epsilon but to remain the same as the step before and I also want to keep the list of intermediate results. Can someone help me ?

Upvotes: 0

Views: 527

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183873

Since you want to keep the intermediate results, the direct translation from what I gather to be the intent is

scanl (\exp x -> if (isLetter x) then update exp (Literal x) "" else Epsilon) Epsilon "a+b+c+"

The type of scanl is

Prelude> :t scanl
scanl :: (a -> b -> a) -> a -> [b] -> [a]

the first argument is a function to combine the current "state" and the next list element, the second is the initial "state". So the above updates the "state" using the function you supplied, adjusted to take two arguments.

I'm not sure that you really want to reset the accumulator to Epsilon for each non-letter, if not, you'd need to change the combining function, maybe

\exp x -> if (isLetter x) then update exp (Literal x) "" else exp

to keep the old value of the accumulator for non-letters.

Upvotes: 3

Related Questions