dimanche 25 février 2018

The expressiveness of fold(r)?

I am working of kind of blog-post/paper regarding fold. Mostly I stick to fold : (a -> b -> b) -> b -> [a] -> b signature, however fold-left might work as well.

What I need is as many examples as possible, where fold used to implement well-known and commonly used bits like:

sum = foldr (+) 0

product = foldr (*) 1

any = foldr (||) False

all = foldr (&&) True

(++ ys) = foldr (:) ys

length = foldr (\_ n -> n + 1) 0

reverse = foldr (\x xs -> xs ++ [x]) []

map f = foldr (\x xs -> f x : xs) []

filter p = foldr (\x xs -> if p x then x : xs else xs) []

All the examples above are written and tested in Haskell, however I can accept any language, including OO-ones.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire