====== Either ======
* example code
main :: IO ()
main =
do
print $ f ""
print $ f "2"
print $ f "23"
print $ f "235"
print $ f "2345"
print $ f "2345a"
print $ f "a2345"
print $ f "a"
print $ f "1a"
print $ f "a1"
f :: String -> Either String Int
f lch = f' lch 0
where
f' :: String -> Int -> Either String Int
f' [] niAccu = Left "empty"
f' [ch] niAccu = f'' ch >>= (\ni -> return ((niAccu * 10) + ni))
f' (ch0:ch1:lrch) niAccu = f'' ch0 >>= (\ni0 -> f' (ch1:lrch) ((niAccu * 10) + ni0))
f'' :: Char -> Either String Int
f'' '0' = Right 0
f'' '1' = Right 1
f'' '2' = Right 2
f'' '3' = Right 3
f'' '4' = Right 4
f'' '5' = Right 5
f'' '6' = Right 6
f'' '7' = Right 7
f'' '8' = Right 8
f'' '9' = Right 9
f'' _ = Left "not a number"
* output:
Left "empty"
Right 2
Right 23
Right 235
Right 2345
Left "not a number"
Left "not a number"
Left "not a number"
Left "not a number"
Left "not a number"
===== ✎ =====
~~DISCUSSION~~