|
| 1 | +{-# LANGUAGE FlexibleInstances #-} |
| 2 | + |
| 3 | +module Chapter11Phone where |
| 4 | + |
| 5 | +import qualified Data.Char as C |
| 6 | +import qualified Data.Text as T |
| 7 | + |
| 8 | + |
| 9 | +type NextInputCharIsUpper = Bool |
| 10 | +type OutputChoices = () -> [Char] |
| 11 | + |
| 12 | +data KeyBuffer = EmptyKeyBuffer | PressedKeyBuffer Char Int OutputChoices deriving (Show) |
| 13 | + |
| 14 | +data TextpadST = TextpadST T.Text KeyBuffer NextInputCharIsUpper deriving (Show) |
| 15 | + |
| 16 | + |
| 17 | +instance Show OutputChoices where |
| 18 | + show f = show (take 5 (f ()) ++ "...") |
| 19 | + |
| 20 | + |
| 21 | +pressTextpadKey :: TextpadST -> Char -> TextpadST |
| 22 | +pressTextpadKey tp key = |
| 23 | + case C.toUpper key of |
| 24 | + '1' -> appendChar (acceptKeyBuffer tp) '1' |
| 25 | + '2' -> pressKey tp '2' (\() -> cycle ['a'..'c']) |
| 26 | + '3' -> pressKey tp '3' (\() -> cycle ['d'..'f']) |
| 27 | + '4' -> pressKey tp '4' (\() -> cycle ['g'..'i']) |
| 28 | + '5' -> pressKey tp '5' (\() -> cycle ['j'..'l']) |
| 29 | + '6' -> pressKey tp '6' (\() -> cycle ['m'..'o']) |
| 30 | + '7' -> pressKey tp '7' (\() -> cycle ['p'..'s']) |
| 31 | + '8' -> pressKey tp '8' (\() -> cycle ['t'..'v']) |
| 32 | + '9' -> pressKey tp '9' (\() -> cycle ['w'..'z']) |
| 33 | + '*' -> toogleCase tp |
| 34 | + '0' -> pressKey tp '0' (\() -> cycle ['+', ' ']) |
| 35 | + '#' -> pressKey tp '#' (\() -> cycle ['.', ',']) |
| 36 | + 'P' -> acceptKeyBuffer tp |
| 37 | + _ -> tp |
| 38 | + |
| 39 | +pressTextpadKeys :: String -> TextpadST |
| 40 | +pressTextpadKeys = foldl pressTextpadKey (TextpadST T.empty EmptyKeyBuffer False) |
| 41 | + |
| 42 | +pressKey :: TextpadST -> Char -> OutputChoices -> TextpadST |
| 43 | +pressKey (TextpadST txt EmptyKeyBuffer nextInputCharIsUpper) c oc = TextpadST txt (PressedKeyBuffer c 1 oc) nextInputCharIsUpper |
| 44 | +pressKey tp@(TextpadST txt (PressedKeyBuffer c' count oc') nextInputCharIsUpper) c oc = |
| 45 | + if c == c' |
| 46 | + then TextpadST txt (PressedKeyBuffer c' (count + 1) oc') nextInputCharIsUpper |
| 47 | + else pressKey (acceptKeyBuffer tp) c oc |
| 48 | + |
| 49 | +toogleCase :: TextpadST -> TextpadST |
| 50 | +toogleCase (TextpadST txt keyBuffer nextInputCharIsUpper) = TextpadST txt keyBuffer (not nextInputCharIsUpper) |
| 51 | + |
| 52 | +acceptKeyBuffer :: TextpadST -> TextpadST |
| 53 | +acceptKeyBuffer (TextpadST txt EmptyKeyBuffer nextInputCharIsUpper) = TextpadST txt EmptyKeyBuffer nextInputCharIsUpper |
| 54 | +acceptKeyBuffer tp@(TextpadST _ (PressedKeyBuffer _ count oc') _) = appendChar tp (oc' () !! (count - 1)) |
| 55 | + |
| 56 | +appendChar :: TextpadST -> Char -> TextpadST |
| 57 | +appendChar (TextpadST txt _ nextInputCharIsUpper) c = TextpadST (T.snoc txt (setCase c)) EmptyKeyBuffer False |
| 58 | + where setCase = if nextInputCharIsUpper then C.toUpper else id |
0 commit comments