Skip to content

Instantly share code, notes, and snippets.

@levinotik
Created January 19, 2016 02:31
Show Gist options
  • Save levinotik/545fd264cd262549fd78 to your computer and use it in GitHub Desktop.
Save levinotik/545fd264cd262549fd78 to your computer and use it in GitHub Desktop.
Explicit recursion vs Folding
module Folding where
import Prelude hiding (length, sum, maximum, elem, null, product, reverse, all, any, (++), map, init, filter)
sum :: Num a => [a] -> a
sum [] = 0
sum (x:xs) = x + sum xs
sum' :: Num a => [a] -> a
sum' = foldl (+) 0
product :: Num a => [a] -> a
product [] = 1
product (x:xs) = x * product xs
product' :: Num a => [a] -> a
product' = foldl (*) 1
length :: [a] -> Int
length [] = 0
length (_:xs) = 1 + length xs
length' :: [a] -> Int
length' = foldl (\acc _ -> acc + 1) 0
elem :: Eq a => a -> [a] -> Bool
elem _ [] = False
elem a (x:xs) = a == x || elem a xs
elem' :: Eq a => a -> [a] -> Bool
elem' a = foldl (\b x -> b || x == a) False
null :: [a] -> Bool
null [] = True
null _ = False
null' :: [a] -> Bool
null' = foldl (\_ _ -> False) True
reverse :: [a] -> [a]
reverse = foldl flip (:) []
all :: (a -> Bool) -> [a] -> Bool
all _ [] = True
all p (a:as) = p a && all p as
all' :: (a -> Bool) -> [a] -> Bool
all' p = foldl (\b a -> b && p a) True
any :: (a -> Bool) -> [a] -> Bool
any _ [] = False
any p (a:as) = p a || any p as
any' :: (a -> Bool) -> [a] -> Bool
any' p = foldl (\b a -> b || p a) False
filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter p (x:xs) = if p x then x : filter p xs else filter p xs
filter' :: (a -> Bool) -> [a] -> [a]
filter' p = foldr (\a l -> if p a then a : l else l) []
init :: [a] -> Maybe [a]
init xs = if null xs then Nothing else Just (initSafe xs)
where initSafe [x] = []
initSafe (x:xs) = x : initSafe xs
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (a:as) = f a : map f as
map' :: (a -> b) -> [a] -> [b]
map' f = foldr (\a l -> f a : l) []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment