diff options
Diffstat (limited to 'src/Common.hs')
-rw-r--r-- | src/Common.hs | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/src/Common.hs b/src/Common.hs new file mode 100644 index 0000000..a196527 --- /dev/null +++ b/src/Common.hs @@ -0,0 +1,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 |