I have a problem with one of the Haskell basics: Fold + anonymous functions
I’m developing a bin2dec program with foldl.
The solution looks like this:
bin2dec :: String -> Int
bin2dec = foldl (\x y -> if y=='1' then x*2 + 1 else x*2) 0
I understand the basic idea of foldl / foldr but I can’t understand what the parameters x y stands for.
See the type of
foldlfoldl :: (a -> b -> a) -> a -> [b] -> aConsider
foldl f z listso foldl basically works incrementally on the list (or anything foldable), taking 1 element from the left and applying
f z elementto get the new element to be used for the next step while folding over the rest of the elements. Basically a trivial definition of foldl might help understanding it.The diagram from Haskell wiki might help building a better intuition.
Consider your function
f = (\x y -> if y=='1' then x*2 + 1 else x*2)and try to write the trace forfoldl f 0 "11". Here"11"is same as['1','1']Now f is a function which takes 2 arguments, first a integer and second a character and returns a integer.
So In this case
x=0andy='1', sof x y = 0*2 + 1 = 1Now again applying
f 1 '1'. Herex=1andy='1'sof x y = 1*2 + 1 = 3.Using the first definition of
foldlfor empty list.Which is the decimal representation of “11”.