New to Haskell and Functional Programming
In Haskell (ghci) what does scanl do in the following expressions?
scanl (+) 0 [1,3..]
scanl (*) 1 [1..]
At first I thought it makes an infinite list of odd numbers where it successively adds them however this doesn't sound right. What does both those expressions do?
Thank you
scanl
is just like foldl
except for it gives you a list of intermediate results instead of just the final one. Understanding it helps understanding foldl
and vice versa. So, for example, whereas foldl (+) 0
finds the sum of all elements of a list, scanl (+) 0
shows you all the intermediate sums leading up to it:
ghci> scanl (+) 0 [1,1,1,2,5]
[0, 1, 2, 3, 5, 10]
-- +1 +1 +1 +2 +5
Similarly, since foldl (++) ""
concatenates a bunch of stirngs, scanl (++) ""
shows you the intermediate concatenations:
ghci> scanl (++) "" ["foo", "bar", "baz", "quux"]
["", "foo", "foobar", "foobarbaz", "foobarbazquux"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.