-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapplicative-parser.hs
48 lines (36 loc) · 1.19 KB
/
applicative-parser.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import Data.Maybe
import Data.List
import Control.Applicative
import Control.Monad
import Control.Arrow
import Control.Monad.Trans.State
lookupDelete k [] = Nothing
lookupDelete k ((x, y):xys)
| k == x = Just (y, xys)
| otherwise = second ((x, y):) <$> lookupDelete k xys
finish (x, []) = Just x
finish _ = Nothing
type Parser a = StateT [(String, String)] Maybe a
option :: (String -> Maybe a) -> String -> Parser a
option f str = StateT $ \xs -> do
(v, xs') <- lookupDelete str xs
v' <- f v
return (v', xs')
string :: String -> Parser String
string = option Just
value :: Read a => String -> Parser a
value = option $ reads >>> listToMaybe >=> finish
optPairs [] = Just []
optPairs (('-':'-':x1):x2:xs) = ((x1, x2) :) <$> optPairs xs
optPairs _ = Nothing
parse :: Parser a -> String -> Maybe a
parse p = words >>> optPairs >=> runStateT p >=> finish
-- An example.
data User = User
{ userName :: String
, userId :: Integer
, userDbls :: (Double, Double)
} deriving Show
userParser :: Parser User
userParser = User <$> string "name" <*> value "id" <*> value "dbls"
main = interact $ unlines . map (show . parse userParser) . lines