Parameters in anonymous function

The fold function in fold takes as parameters the accumulator x, and the element y. So there is no z that is passed.

But even if that was somehow possible, there are still other issues. x is the accumulator here, so a list, that means that x : y makes no sense, since (:) :: a -> [a] -> [a] takes an element and a list, and constructs a new list.

You can however easily make use of foldr to implement a takeWhile function. Indeed:

takeWhile' p = foldr (\x -> if p x then (x :) else const []) []

We here thus check if the predicate holds, if that is the case, we preprend the accumulator with x. If not, we return [], regardless of the value of the accumulator.

Due to the laziness of foldr, it will not look for elements after an element has failed the accumulator, since const [] will ingore the value of the accumulator.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top