Skip to content

Instantly share code, notes, and snippets.

@willbasky
Created March 27, 2019 19:36
Show Gist options
  • Save willbasky/51706537d58756de47f2fd50545a6f78 to your computer and use it in GitHub Desktop.
Save willbasky/51706537d58756de47f2fd50545a6f78 to your computer and use it in GitHub Desktop.
data DatabaseItem = DbString String | DbNumber Integer | DbDate UTCTime
deriving (Eq, Ord, Show)
theDatabase :: [DatabaseItem]
theDatabase =
[ DbDate (UTCTime (fromGregorian 1911 5 1) (secondsToDiffTime 34123))
, DbNumber 9001
, DbString "Hello, world!"
, DbDate (UTCTime (fromGregorian 1921 5 1) (secondsToDiffTime 34123))
]
-- 1. Write a function that filters for DbDate values and returns a list
-- of the UTCTime values inside them.
filterDbDate :: [DatabaseItem] -> [UTCTime]
filterDbDate = foldr foo []
where
foo db acc = case db of
DbDate x -> x : acc
_ -> acc
-- 2. Write a function that filters for DbNumber values and returns a list
-- of the Integer values inside them.
filterDbNumber :: [DatabaseItem] -> [Integer]
filterDbNumber = foldr foo []
where
foo db acc = case db of
DbNumber x -> x : acc
_ -> acc
-- 3. Write a function that gets the most recent date.
mostRecent :: [DatabaseItem] -> UTCTime
mostRecent = maximum . foldr foo []
where
foo db acc = case db of
DbDate x -> x : acc
_ -> acc
mostRecent2 :: [DatabaseItem] -> UTCTime
mostRecent2 = foldr foo utcEmpty
where
utcEmpty = UTCTime (fromGregorian 0 1 1) (secondsToDiffTime 0)
foo db acc = case db of
DbDate x -> max x acc
_ -> acc
-- 4. Write a function that sums all of the DbNumber values.
sumDb :: [DatabaseItem] -> Integer
sumDb = foldr foo 0
where
foo db acc = case db of
DbNumber x -> x + acc
_ -> acc
-- 5. Write a function that gets the average of the DbNumber values.
-- You'll probably need to use fromIntegral
-- to get from Integer to Double.
avgDb :: [DatabaseItem] -> Double
avgDb = (\(s,n) -> fromIntegral s / n) . foldr foo (0,0)
where
foo db (acc,n) = case db of
DbNumber x -> (x + acc, 1 + n)
_ -> (acc,n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment