praxis

Various programming exercises.
git clone git://git.jtobin.io/praxis.git
Log | Files | Refs

Number.hs (1029B)


      1 {-# OPTIONS_GHC -Wall #-}
      2 
      3 import Data.Char as C
      4 
      5 esum :: String -> Int
      6 esum = sum . grab
      7 
      8 grab :: String -> [Int]
      9 grab = loop [] Nothing where
     10   loop acc prev list = case list of
     11     []          -> reverse $ case prev of
     12       Nothing  -> acc
     13       Just num ->
     14         let parsed = parse (reverse num)
     15         in  parsed : acc
     16 
     17     (curr:rest) -> case prev of
     18       Nothing ->
     19         if   C.isDigit curr
     20         then loop acc (Just [curr]) rest
     21         else loop acc Nothing rest
     22 
     23       Just num ->
     24         if   C.isDigit curr
     25         then loop acc (Just (curr : num)) rest
     26         else
     27           let parsed = parse (reverse num)
     28           in  loop (parsed : acc) Nothing rest
     29 
     30 parse :: String -> Int
     31 parse =
     32     snd . foldr alg (1, 0)
     33   where
     34     alg char (base, acc) =
     35       let nbase = base * 10
     36           nacc  = acc + C.digitToInt char * base
     37       in  (nbase, nacc)
     38 
     39 test0 :: String
     40 test0 = "11aa22bb33cc44"
     41 
     42 test1 :: String
     43 test1 = "1k23jk34jk56jk3454"
     44 
     45 main :: IO ()
     46 main = do
     47   print (esum test0)
     48   print (esum test1)