Search code examples
haskellfold

Haskell ,implement any function with foldr


I am trying to imlpment a function, that gives True, when at least one element in the list fulfilled the condition (>5)

*Main> any (>5) [1..]
True

This is my code which is working:

any1 f [] = True
any1 f (x:xs) = f x || any f xs

but I want to implement it with foldr, how can I do it? Thanks for helping.


Solution

  • A foldr pattern on a list basically replaces:

    foldr f z [x1, x2, …, xn]

    with:

    f x1 (f x2 (… (f xn z) …))

    It thus replaces the "cons" constructor (:) with f, and the empty list [] with z.

    You thus should look how any1 f has a value on which it maps for the empty list, and define a function g that takes as first parameter an element xi and a second element the result of foldr g [xi+1, xi+2, …, xn]:

    any1 :: Foldable f => (a -> Bool) -> f a -> Bool
    any1 f = foldr g …
        where g … = …

    where you need to fill in .