Last active
August 29, 2015 14:16
-
-
Save Svetixbot/8c9ff60dd80e47a6cb7d to your computer and use it in GitHub Desktop.
Implementation of some of the functions from Modules #learnyouahaskell
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
-- places a separator between each element of an array and produces new array | |
intersperse' :: a -> [a] -> [a] | |
intersperse' _ [] = [] | |
intersperse' a (x:xs) = x : a : intersperse' a xs | |
-- takes a list of lists and a list. | |
-- It then inserts that list in between all those lists and then flattens the result | |
intercalate' :: [a] -> [[a]] -> [a] | |
intercalate' _ [] = [] | |
intercalate' l1 (x:[]) = x | |
intercalate' l1 (x:xs) = x ++ l1 ++ intercalate' l1 xs | |
-- flattens a list of lists into just a list of elements. | |
concat' :: [[a]] -> [a] | |
concat' [] = [] | |
concat' (x:xs) = x ++ concat' xs | |
-- The same as first mapping a function to a list and then concatenating the list with concat. | |
concatMap' :: (a -> [a]) -> [a] -> [a] | |
concatMap' _ [] = [] | |
concatMap' f (x:xs) = f x ++ concatMap' f xs | |
-- Takes a list of boolean values and returns True only if all the values in the list are True. | |
and' :: [Bool] -> Bool | |
and' [] = False | |
and' (True:[]) = True | |
and' (False:xs) = False | |
and' (True:xs) = and' xs | |
-- Is like and, only it returns True if any of the boolean values in a list is True. | |
or' :: [Bool] -> Bool | |
or' [] = False | |
or' (True:xs) = True | |
or' (False:xs) = or' xs | |
-- Takes a function and a starting value. | |
-- It applies the function to the starting value, | |
-- then it applies that function to the result, then it applies the function to that result again, etc. It returns all the results in the form of an infinite list. | |
-- Ex: take 10 $ iterate (*2) 1 => [1,2,4,8,16,32,64,128,256,512] | |
iterate' :: (a -> a) -> a -> [a] | |
iterate' f a = f a : iterate' f a | |
-- Is a really useful little function. | |
-- It takes elements from a list while the predicate holds | |
-- and then when an element is encountered that doesn't satisfy the predicate, it's cut off | |
takeWhile' :: (a -> Bool) -> [a] -> [a] | |
takeWhile' _ [] = [] | |
takeWhile' f (x:xs) | |
| f x = x : takeWhile' f xs | |
| otherwise = [x] | |
-- It drops all the elements while the predicate is true. | |
-- Once predicate equates to False, it returns the rest of the list. | |
dropWhile' :: (a -> Bool) -> [a] -> [a] | |
dropWhile' _ [] = [] | |
dropWhile' f (x:xs) | |
| f x = dropWhile' f xs | |
| otherwise = xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment