Skip to content

Instantly share code, notes, and snippets.

@meikj
Last active January 3, 2016 01:19
Show Gist options
  • Save meikj/8388331 to your computer and use it in GitHub Desktop.
Save meikj/8388331 to your computer and use it in GitHub Desktop.
-- Question 1: Define the functions add and allEqual
add :: (Int -> Int) -> Int -> Int
add f 1 = f 1
add f n = if n > 0 then add f (n-1) + f n else error "input must be n > 0"
allEqual :: (Int -> Int) -> Int -> Bool
allEqual f 1 = True
allEqual f n = if n > 0 then (allEqual f (n-1)) && (f (n-1) == f n) else error "input must be n > 0"
-- Question 2: Use fold to define fac and maxList
fold :: (a -> b -> a) -> a -> [b] -> a
fold f a [] = a
fold f a (x:xs) = fold f (f a x) xs
fac :: Int -> Int
fac n = fold (*) 1 [1..n]
maxList :: [Int] -> Int
maxList xs = fold (max) 0 xs
-- Question 3: Define the function numeral and its inverse
-- numeral2
numeral :: [Int] -> Int
numeral xs = fold f 0 xs
where f a x = if a == 0 then x else a * 10 + x
numeral2 :: Int -> [Int]
numeral2 0 = []
numeral2 n = numeral2 (n `div` 10) ++ [n `mod` 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment