[Haskell-beginners] Iterate in terms of scanl

Atrudyjane atrudyjane at protonmail.com
Mon Oct 24 01:37:14 UTC 2016


Hello All,

Sorry about my previous post, email was hosed. I was working on a homework problem where the task is to write the iterate function in terms of scanl. Came up with this:

myIterate f x = scanl (const.f) x (repeat x)

I went looking around for other solutions to check my work and found the following solution on the Haskell Wiki:

iterate f x = scanl f x (repeat x)

myIterate seems to work checked against the Prelude iterate but I don't know if it's a good solution or not, because the iterate solution on the Haskell Wiki throws a type error. Types of Prelude iterate and scanl are different, so I can see why, or am I missing something? Here is some REPL output:

Prelude iterate:
λ> take 10 (iterate (+1) 1)
[1,2,3,4,5,6,7,8,9,10]

myIterate:
λ> take 10 (myIterate (+1) 1)
[1,2,3,4,5,6,7,8,9,10]

Haskell Wiki solution:
λ> take 10 (iterate' (+1) 1)
error:
• Occurs check: cannot construct the infinite type: a ~ a -> a
Expected type: a -> a -> a
Actual type: (a -> a) -> a -> a
• In the first argument of ‘iterate'’, namely ‘(+ 1)’
In the second argument of ‘take’, namely ‘(iterate' (+ 1) 1)’
In the expression: take 10 (iterate' (+ 1) 1)
• Relevant bindings include it :: [a] (bound at <interactive>:63:1)

It will work if you pass it a function that takes two parameters though:

λ> take 10 (iterate' (+) 1)
[1,2,3,4,5,6,7,8,9,10]

Any thoughts would be much appreciated!

Andrea
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20161023/b70ca7a9/attachment.html>


More information about the Beginners mailing list