简体   繁体   English

Haskell - `scanl` 在这个表达式中做了什么

[英]Haskell - What does `scanl` do in this expression

New to Haskell and Functional Programming Haskell 和函数式编程的新手

In Haskell (ghci) what does scanl do in the following expressions?在 Haskell (ghci) 中, scanl 在以下表达式中做了什么?

  • 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. scanl就像foldl一样,除了它给你一个中间结果列表,而不是最后一个。 Understanding it helps understanding foldl and vice versa.理解它有助于理解foldl ,反之亦然。 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:因此,例如,虽然foldl (+) 0查找列表中所有元素的总和,但scanl (+) 0显示导致它的所有中间总和:

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:类似地,由于foldl (++) ""连接了一堆stirngs,所以 scanl scanl (++) ""显示了中间连接:

ghci> scanl (++) "" ["foo", "bar", "baz", "quux"]
["", "foo", "foobar", "foobarbaz", "foobarbazquux"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM