Last active
August 29, 2015 14:19
-
-
Save kevinadi/d71c0420d9b0161f47b0 to your computer and use it in GitHub Desktop.
Haskell: learning how basic functions work
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fold' :: (b->a->b) -> b -> [a] -> b | |
fold' f b [] = b | |
fold' f b (h:t) = fold' f (f b h) t | |
map' :: (a->b) -> [a] -> [b] | |
map' f lst = fold' (\b a -> b ++ [f a]) [] lst | |
map'' :: (a->b) -> [a] -> [b] | |
map'' f [] = [] | |
map'' f (h:t) = f h : map'' f t | |
filter' :: (a->Bool) -> [a] -> [a] | |
filter' f lst = fold' (\b a -> if (f a) then b++[a] else b) [] lst | |
filter'' :: (a->Bool) -> [a] -> [a] | |
filter'' f [] = [] | |
filter'' f (h:t) = if (f h) then (h : filter'' f t) else (filter'' f t) | |
all' :: (a->Bool) -> [a] -> Bool | |
all' f lst = fold' (\b a -> b && f a) True lst | |
any' :: (a->Bool) -> [a] -> Bool | |
any' f lst = fold' (\b a -> b || f a) False lst | |
zip' :: [a] -> [b] -> [(a,b)] | |
zip' [] l = [] | |
zip' l [] = [] | |
zip' (h1:t1) (h2:t2) = [(h1,h2)] ++ zip' t1 t2 | |
zipWith' :: (a->b->c) -> [a] -> [b] -> [c] | |
zipWith' f [] l = [] | |
zipWith' f l [] = [] | |
zipWith' f (h1:t1) (h2:t2) = [(f h1 h2)] ++ zipWith' f t1 t2 | |
drop' :: Int -> [a] -> [a] | |
drop' n [] = [] | |
drop' 0 xs = xs | |
drop' n xs = drop' (n-1) (tail xs) | |
take' :: Int -> [a] -> [a] | |
take' n [] = [] | |
take' 0 xs = [] | |
take' n xs = head xs : take' (n-1) (tail xs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment