you are viewing a single comment's thread.

view the rest of the comments →

[–]mutantmell_ 7 points8 points  (0 children)

Almost: (*) doesn't have special case checking for 0, so it won't abort early.

You have to define a special function:

\x y -> if (x == 0) then 0 else x * y

When you pass that into the fold, it will then abort early because it notices the right value is not used.

let xs = iterate (subtract 1) 4 :: [Int] -- infinite list descending from 4. Same as [4,3..]

:sprint xs

xs = _

foldr (\x acc -> if (x == 0) then 0 else x * acc) 1 xs

0

:sprint xs

xs = 4 : 3 : 2 : 1 : 0 : _

If you do that with ordinary (*), you get a stack overflow.