werkt
[cc1516.git] / yard.icl
1 implementation module yard
2
3 import StdTuple
4 import StdClass
5 import Data.Functor
6 import Data.Either
7 import Control.Monad
8 import Control.Applicative
9 from Data.Func import $
10
11 runParser :: (Parser a b) [a] -> (Either Error b, [a])
12 runParser (Parser f) i = f i
13
14 instance Functor (Parser a) where
15 //fmap f m = liftM f m
16 fmap g p = Parser \i -> case runParser p i of
17 (Right r, rest) = (Right $ g r, rest)
18 (Left e, rest) = (Left e, rest)
19
20 instance Applicative (Parser a) where
21 pure a = Parser \i -> (Right a, i)
22 //(<*>) sf p = ap sf p
23 (<*>) pf p = Parser \i -> case runParser pf i of
24 (Right f, rest) = runParser (fmap f p) rest
25 (Left e, rest) = (Left e, rest)
26
27 instance Monad (Parser a) where
28 bind p f = Parser \i -> case runParser p i of
29 (Right r, rest) = runParser (f r) rest
30 (Left e, rest) = (Left e, rest)
31
32 //some, many, optional and l
33 instance Alternative (Parser a) where
34 empty = Parser \i -> (Left ParseException, i)
35 (<|>) p1 p2 = Parser \i -> case runParser p1 i of
36 (Right r, rest) = (Right r, rest)
37 (Left _, rest) = runParser p2 i
38
39 fail :: Parser a b
40 fail = empty
41
42 top :: Parser a a
43 top = Parser \i -> case i of
44 [] = (Left ParseException, [])
45 [x:xs] = (Right x, xs)
46
47 satisfy :: (a -> Bool) -> Parser a a
48 satisfy f = top >>= \r -> if (f r) (return r) fail
49
50 item :: a -> Parser a a | Eq a
51 item a = satisfy ((==)a)
52
53 list :: [a] -> Parser a [a] | Eq a
54 list as = mapM item as