aboutsummaryrefslogtreecommitdiff
path: root/src/Common.hs
blob: a196527701b00a427f2e274dd378bd24f223be83 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
module Common ((?), (?:), fromDigits, leftPad, listToProse, asOrdinal, showDayOfWeek, showMonth) where

import Data.List (replicate, take)
import Data.List.NonEmpty (NonEmpty ((:|)))
import Data.Maybe (fromMaybe)
import Intro

fromDigits :: [Int] -> Int
fromDigits = foldl (\n d -> 10 * n + d) 0

leftPad :: Int -> a -> [a] -> [a]
leftPad m x xs = replicate (m - length ys) x ++ ys
 where
  ys = take m xs

(?) :: Bool -> a -> a -> a
(?) True x _ = x
(?) False _ y = y

infixr 1 ?

(?:) :: Maybe a -> a -> a
maybeA ?: b = fromMaybe b maybeA

infixr 0 ?:

listToProse :: NonEmpty String -> String
listToProse (x :| xs) = mconcat . reverse $ proseJoin xs [x]
 where
  proseJoin [] ys = ys
  proseJoin [y] [] = [y]
  proseJoin [y] zs = y : " and " : zs
  proseJoin (y : ys) zs = proseJoin ys (y : ", " : zs)

asOrdinal :: Int -> String
asOrdinal 11 = "11th"
asOrdinal 12 = "12th"
asOrdinal 13 = "13th"
asOrdinal n =
  show n ++ case n `mod` 10 of
    1 -> "st"
    2 -> "nd"
    3 -> "rd"
    _ -> "th"

showDayOfWeek :: Int -> Maybe String
showDayOfWeek = \case
  0 -> Just "Sunday"
  1 -> Just "Monday"
  2 -> Just "Tuesday"
  3 -> Just "Wednesday"
  4 -> Just "Thursday"
  5 -> Just "Friday"
  6 -> Just "Saturday"
  _ -> Nothing

showMonth :: Int -> Maybe String
showMonth = \case
  1 -> Just "January"
  2 -> Just "February"
  3 -> Just "March"
  4 -> Just "April"
  5 -> Just "May"
  6 -> Just "June"
  7 -> Just "July"
  8 -> Just "August"
  9 -> Just "September"
  10 -> Just "October"
  11 -> Just "November"
  12 -> Just "December"
  _ -> Nothing