Skip to content

Instantly share code, notes, and snippets.

@beeleebow
Last active August 2, 2018 22:55
Show Gist options
  • Save beeleebow/eb6e1829bfb0826da8cd4fde07842714 to your computer and use it in GitHub Desktop.
Save beeleebow/eb6e1829bfb0826da8cd4fde07842714 to your computer and use it in GitHub Desktop.
cis194 w03 solutions

What is this?

Solutions to the week 3 homework exercises in Brent Yorgey's 2013 offering of cis194. The focus of this week was to use higher order functions and move away from heavy usage of recursion and pattern matching.

These solutions use the (.) function which had not yet been coverered at this point in the course. You can find plenty of information about comopse on the interwebs and can of course start your investigation in ghci with :t (.).

Links

module Week03.Golf
( skips
, localMaxima
, histogram
, histogramGen
) where
skips :: [a] -> [[a]]
skips xs = map (`everyNth` xs) [1..(length xs)]
where everyNth n = map snd . filter ((==0) . (`mod` n) . fst) . zip [1..]
localMaxima :: [Integer] -> [Integer]
localMaxima = map (\(_, x, _) -> x) . filter (\(x, y, z) -> y > x && y > z) . triples
where
triples (x:y:z:rs) = (x,y,z) : triples (y:z:rs)
triples _ = []
-- general version that allows for any domain, not just 0..9
-- e.g. putStr (histogramGen [0..3] [0,0,1,2,2,2,3])
histogramGen :: [Integer] -> [Integer] -> String
histogramGen domain xs =
let
freq n = length . filter (== n)
freqs = map (`freq` xs) domain
buildRow n = map (\f -> if f >= n then '*' else ' ') freqs
rows = map buildRow (reverse [1..(maximum freqs)])
separator = take (length domain) (repeat '=')
legend = foldl (++) "" (map show domain)
in
unlines (rows ++ [separator, legend])
histogram :: [Integer] -> String
histogram = histogramGen [0..9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment