-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter10database.hs
45 lines (33 loc) · 1.17 KB
/
chapter10database.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import Data.Time
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))
]
itemToTime :: DatabaseItem -> [UTCTime]
itemToTime (DbDate t) = [t]
itemToTime _ = []
filterDbDate :: [DatabaseItem] -> [UTCTime]
filterDbDate dis = foldr (\a b -> (itemToTime a) ++ b) [] dis
itemToNumber :: DatabaseItem -> [Integer]
itemToNumber (DbNumber n) = [n]
itemToNumber _ = []
filterDbNumber :: [DatabaseItem] -> [Integer]
filterDbNumber dis = foldr (\a b -> (itemToNumber a) ++ b) [] dis
mostRecent :: [DatabaseItem] -> UTCTime
mostRecent dis = maximum (filterDbDate theDatabase)
sumDb :: [DatabaseItem] -> Integer
sumDb dis = sum (filterDbNumber theDatabase)
avgDb :: [DatabaseItem] -> Double
avgDb dis = (fromIntegral (sum numbers)) / (fromIntegral (length numbers))
where numbers = filterDbNumber theDatabase