curry gotcha
[cc1516.git] / yard.icl
1 implementation module yard
2
3 import StdTuple
4 import StdClass
5 import StdString
6 import StdList
7 import StdInt
8 from Data.List import intersperse
9 from Text import instance Text String, class Text(concat)
10 import Data.Functor
11 import Data.Either
12 import Control.Monad
13 import Control.Applicative
14 from Data.Func import $
15 import Data.Void
16
17 instance toString Error where
18 toString (PositionalError l c e) =
19 concat [toString l,":",toString c,": ",e, "\n"]
20 toString (Error e) = concat ["-:-: ", e, "\n"]
21
22 runParser :: (Parser a b) [a] -> (Either Error b, [a])
23 runParser (Parser f) i = f i
24
25 instance Functor (Parser a) where
26 fmap f m = liftM f m
27
28 instance Applicative (Parser a) where
29 pure a = Parser \i -> (Right a, i)
30 (<*>) sf p = ap sf p
31
32 instance Monad (Parser a) where
33 bind p f = Parser \i -> case runParser p i of
34 (Right r, rest) = runParser (f r) rest
35 (Left e, _) = (Left e, i)
36
37 instance Alternative (Parser a) where
38 empty = Parser \i -> (Left $ Error "" , i)
39 (<|>) p1 p2 = Parser \i -> case runParser p1 i of
40 (Right r, rest) = (Right r, rest)
41 (Left e1, rest) = case runParser p2 i of
42 (Left e2, rest) = (Left e2, i)
43 (Right r, rest) = (Right r, rest)
44
45 //Try parser, if it fails decorate the error with the given String and position
46 (<?>) :: (Parser a b) Error -> Parser a b
47 (<?>) p e = Parser \i -> case runParser p i of
48 (Left e1, rest) = (Left e, rest)
49 (Right r, rest) = (Right r, rest)
50
51 fail :: Parser a b
52 fail = empty
53
54 top :: Parser a a
55 top = Parser \i -> case i of
56 [] = (Left $ Error "", [])
57 [x:xs] = (Right x, xs)
58
59 peek :: Parser a a
60 peek = Parser \i -> case i of
61 [] = (Left $ Error "", [])
62 [x:xs] = (Right x, [x:xs])
63
64 (until) infix 2 :: (Parser a b) (Parser a c) -> Parser a [b]
65 (until) p guard = try $ until` p guard []
66 where
67 until` :: (Parser a b) (Parser a c) [b] -> Parser a [b]
68 until` p guard acc = Parser \i -> case runParser guard i of
69 (Right _, rest) = (Right acc, rest)
70 (Left _, _) = case runParser p i of
71 (Right r, rest) = runParser (until` p guard [r:acc]) rest
72 (Left e, _) = (Left e, i)
73 try :: (Parser a b) -> Parser a b
74 try p = Parser \i -> case runParser p i of
75 (Left e, _) = (Left e, i)
76 (Right r, rest) = (Right r, rest)
77
78 eof :: Parser a Void
79 eof = Parser \i -> case i of
80 [] = (Right Void, [])
81 _ = (Left $ Error "", i)
82
83 satisfy :: (a -> Bool) -> Parser a a
84 satisfy f = top >>= \r -> if (f r) (return r) fail
85
86 check :: (a -> Bool) -> Parser a a
87 check f = peek >>= \r -> if (f r) (return r) fail
88
89 item :: a -> Parser a a | Eq a
90 item a = satisfy ((==)a)
91
92 list :: [a] -> Parser a [a] | Eq a
93 list as = mapM item as