-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path01.getlines.hs
28 lines (22 loc) · 908 Bytes
/
01.getlines.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
import System.IO.Error (tryIOError)
import Data.Char (isDigit, digitToInt)
import Data.List (isPrefixOf, findIndex)
-- An alternative to interact, by using line by line processing using getLine.
--
-- Mostly kept around as a demonstration, for all practical purposes, the normal
-- interact version should be better.
main :: IO ()
main = getLines >>= (print . sum . fmap parse)
getLines :: IO [String]
getLines = tryIOError getLine >>= e
where e (Left _) = pure []
e (Right s) = fmap (s :) getLines
parse :: String -> Int
parse s = first s spelled * 10 + first (reverse s) (map reverse spelled)
first :: String -> [String] -> Int
first s@(c:s') ms = if isDigit c then digitToInt c else
case findIndex (`isPrefixOf` s) ms of
Nothing -> first s' ms
(Just i) -> i + 1
spelled :: [String]
spelled = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]