Skip to content

Instantly share code, notes, and snippets.

@PhyrexTsai
Last active April 23, 2016 16:37
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/a284801daef4f43af89dffeafedc252b to your computer and use it in GitHub Desktop.
Save PhyrexTsai/a284801daef4f43af89dffeafedc252b to your computer and use it in GitHub Desktop.
Function composition.md

Function composition

Use the functions, remdup, elemOcc, and map to define a function, occurrences, that receives a list of characters and returns a list of pairs of an element and the number of its occurrences in the input list. For example:

occurrences [‘a’, ‘c’, ‘d’, ‘a’, ‘c’] = [(‘a’, 2), (‘c’, 2), (‘d’, 1)]
occurrences :: [Char] -> [(Char,Int)]
occurrences xs = zip (??) (??)
remdup :: [Char]->[Char]
remdup [] = []
remdup (x:xs) = x : remdup (…)
elemOcc :: Char-> [Char]->Int
elemOcc x = length . (filter ??)
remdup :: [Char]->[Char]
remdup [] = []
remdup (x:xs) = x : remdup (filter (/=x) (x:xs))
elemOcc :: Char->[Char]->Int
elemOcc k = length . filter (==k)
occurrences :: [Char] -> [(Char, Int)]
occurrences xs = zip [x | x <- remdup xs] [elemOcc x xs | x <- remdup xs]
main = do
print(occurrences ['a', 'b', 'c', 'a', 'c'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment