Skip to content

Instantly share code, notes, and snippets.

@PhyrexTsai
Last active April 23, 2016 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhyrexTsai/651d1766d0b0134da99be1dbdd3c0c8b to your computer and use it in GitHub Desktop.
Save PhyrexTsai/651d1766d0b0134da99be1dbdd3c0c8b to your computer and use it in GitHub Desktop.
Fold functions.md

Fold functions

Use fold-family functions and some auxiliary functions, such as the map, all and any defined in class slides, and your own, to define the following functions. In other words, you cannot use direct recursion to define them.

a. Write a function maxl xs using that generates an error "empty list" if xs==[] and otherwise returns the largest element of xs

maxl :: (Ord a) => [a] -> a
maxl xs = ...
>maxl [1,3,2,5,6,4]
6
>maxl []
Program error: empty list

b. Write a function member x ys which returns True if x is an element of ys, False otherwise. (No direct recursion)

member :: (Eq a) => [a] -> a -> Bool
member xs s = ...
> member [1,2,3] 4
False
> member [1,2,3,4.0,5] 4
True
> member [’a’,’b’,’x’,’z’] ’b’
True
maxl :: (Ord a) => [a] -> a
maxl = foldr1 (\x acc -> if x > acc then x else acc)
main = do
print(maxl [1,3,6,10,2,8])
member :: (Eq a) => [a] -> a -> Bool
member xs x = foldl (\acc y -> if x == y then True else acc) False xs
main = do
print(member [1,3,6,10,2,8] 11)
print(member [1,3,6,10,2,8] 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment