Does "iterate" change the meaning of the applied function?
When I put t开发者_Python百科he following lambda expression in ghci
I get 1
:
ghci> (\x -> x+1) 0
1
But when I use that function with iterate
I get
ghci> take 10 (iterate (\x -> x+1) 0)
[0,1,2,3,4,5,6,7,8,9]
I expected to get a list equal to [1..10]
. Why not?
The first result of iterate is the original input without the function applied, i.e. the function is called 0 times. That's why the result is one off from what you expect.
More specifically, iterate is implemented lie this:
iterate f v = v : iterate f (f v)
Just remember that the start value you give to iterate will appear first in thelist - that's it.
Stop...Hoogle time!
http://haskell.org/hoogle/?hoogle=iterate
click iterate
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:iterate
iterate f x
returns an infinite list of repeated applications off
tox
:iterate f x == [x, f x, f (f x), ...]
There you go. It works that way because that's how it says it works. I'm not trying to be flippant, just hoping to illustrate the usefulness of Hoogle and the docs. (Sounds like a good name for a Haskell band: "Hoogle and the Docs")
精彩评论