| 45 | 45 |
-- | Utility function for parsing a pair of things.
|
| 46 | 46 |
fromPair :: Parse t a -> Parse t b -> Parse t (a, b)
|
| 47 | 47 |
fromPair pl pr (L [l, r]) = (,) <$> pl l <*> pr r
|
| 48 | |
fromPair _ _ sx = fail ("Expected two-element list")
|
| 48 |
fromPair _ _ sx = Left ("Expected two-element list")
|
| 49 | 49 |
|
| 50 | 50 |
-- | Utility function for parsing a list of things.
|
| 51 | 51 |
fromList :: Parse t a -> Parse t [a]
|
| 52 | 52 |
fromList p (L ss) = mapM p ss
|
| 53 | |
fromList _ sx = fail ("Expected list")
|
| 53 |
fromList _ sx = Left ("Expected list")
|
| 54 | 54 |
|
| 55 | 55 |
fromAtom :: Parse t t
|
| 56 | |
fromAtom (L _) = fail "Expected atom; found list"
|
| 56 |
fromAtom (L _) = Left "Expected atom; found list"
|
| 57 | 57 |
fromAtom (A a) = return a
|
| 58 | 58 |
|
| 59 | 59 |
asPair :: ((S t, S t) -> Either String a) -> S t -> Either String a
|
| 60 | 60 |
asPair f (L [l, r]) = f (l, r)
|
| 61 | |
asPair _ sx = fail ("Expected two-element list")
|
| 61 |
asPair _ sx = Left ("Expected two-element list")
|
| 62 | 62 |
|
| 63 | 63 |
asList :: ([S t] -> Either String a) -> S t -> Either String a
|
| 64 | 64 |
asList f (L ls) = f ls
|
| 65 | |
asList _ sx = fail ("Expected list")
|
| 65 |
asList _ sx = Left ("Expected list")
|
| 66 | 66 |
|
| 67 | 67 |
isAtom :: Eq t => t -> S t -> Either String ()
|
| 68 | 68 |
isAtom s (A s')
|
| 69 | 69 |
| s == s' = return ()
|
| 70 | |
| otherwise = fail ".."
|
| 71 | |
isAtom _ _ = fail ".."
|
| 70 |
| otherwise = Left ".."
|
| 71 |
isAtom _ _ = Left ".."
|
| 72 | 72 |
|
| 73 | 73 |
asAtom :: Show t => (t -> Either String a) -> S t -> Either String a
|
| 74 | 74 |
asAtom f (A s) = f s
|
| 75 | |
asAtom _ sx = fail ("Expected atom; got" ++ show sx)
|
| 75 |
asAtom _ sx = Left ("Expected atom; got" ++ show sx)
|
| 76 | 76 |
|
| 77 | 77 |
asAssoc :: Show t => ([(S t, S t)] -> Either String a) -> S t -> Either String a
|
| 78 | 78 |
asAssoc f (L ss) = gatherPairs ss >>= f
|
| 79 | 79 |
where gatherPairs (L [a, b] : ss) = (:) <$> pure (a, b) <*> gatherPairs ss
|
| 80 | 80 |
gatherPairs [] = pure []
|
| 81 | |
gatherPairs _ = fail "..."
|
| 82 | |
asAssoc _ sx = fail ("Expected assoc list; got " ++ show sx)
|
| 81 |
gatherPairs _ = Left "..."
|
| 82 |
asAssoc _ sx = Left ("Expected assoc list; got " ++ show sx)
|
| 83 | 83 |
|
| 84 | 84 |
car :: (S t -> Either String t') -> [S t] -> Either String t'
|
| 85 | 85 |
car f (x:_) = f x
|
| 86 | |
car _ [] = fail "car: Taking car of zero-element list"
|
| 86 |
car _ [] = Left "car: Taking car of zero-element list"
|
| 87 | 87 |
|
| 88 | 88 |
cdr :: ([S t] -> Either String t') -> [S t] -> Either String t'
|
| 89 | 89 |
cdr f (_:xs) = f xs
|
| 90 | |
cdr _ [] = fail "cdr: Taking cdr of zero-element list"
|
| 90 |
cdr _ [] = Left "cdr: Taking cdr of zero-element list"
|