# [Haskell-cafe] Foldr tutorial, Inspired by Getting a Fix from a Fold

Nicolas Frisby nicolas.frisby at gmail.com
Mon Feb 12 10:35:01 EST 2007

```Guess this is a tricky choice for a foldr intro, since it requires a
"paramorphism" (see bananas lenses wires etc.)

para :: (a -> [a] -> b -> b) -> b -> [a] -> b
para f e [] = e
para f e (x:xs) = f x xs (para f e xs)

-- note that the original tail of the list (i.e. xs and not xs') is
used in the else-branch
dropWhile' p = para (\x xs xs' -> if p x then xs' else (x:xs)) []

Prelude> dropWhile' (<5) [1,2,3,4,5,6,7,8]
[5,6,7,8]
Prelude> dropWhile' (<5) [1,2,3,4,5,6,7,1]
[5,6,7,1]
Prelude> :m + Test.QuickCheck
Prelude Test.QuickCheck> :m + Text.Show.Functions
Prelude Test.QuickCheck Text.Show.Functions>
quickCheck \$ \p l -> dropWhile p (l :: [Int]) == dropWhile' p l
OK, passed 100 tests.

On 2/12/07, Donald Bruce Stewart <dons at cse.unsw.edu.au> wrote:
> pixel:
> > Chris Moline <evilantleredthing at yahoo.ca> writes:
> >
> > > dropWhile p = foldr (\x l' -> if p x then l' else x:l') []
> >
> > invalid:  dropWhile (< 5) [1, 10, 1]  should return [10, 1]
>
> Prelude Test.QuickCheck Text.Show.Functions> quickCheck \$ \p xs -> dropWhile p xs == foldr (\x l' -> if p x then l' else x:l') [] (xs :: [Int])
>
> Falsifiable, after 4 tests:
> <function>
> [-1,-3,1]
>
>
> If in doubt, do a quick check!
>
> -- Don
> _______________________________________________