Basic.hs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. {-# LANGUAGE PatternSynonyms #-}
  2. module Data.SCargot.Repr.Basic
  3. ( -- * Basic 'SExpr' representation
  4. R.SExpr(..)
  5. -- * Shorthand Patterns
  6. , pattern (:::)
  7. , pattern A
  8. , pattern Nil
  9. -- * Useful processing functions
  10. , fromPair
  11. , fromList
  12. ) where
  13. import Control.Applicative ((<$>), (<*>), pure)
  14. import Data.SCargot.Repr as R
  15. -- | A shorter infix alias for `SCons`
  16. pattern x ::: xs = SCons x xs
  17. -- | A shorter alias for `SAtom`
  18. pattern A x = SAtom x
  19. -- | A (slightly) shorter alias for `SNil`
  20. pattern Nil = SNil
  21. type S t = R.SExpr t
  22. type Parse t a = R.SExpr t -> Either String a
  23. -- | Utility function for parsing a pair of things.
  24. fromPair :: Parse t a -> Parse t b -> Parse t (a, b)
  25. fromPair pl pr (l ::: r ::: Nil) = (,) <$> pl l <*> pr r
  26. fromPair _ _ sx = fail ("Expected two-element list")
  27. -- | Utility function for parsing a list of things.
  28. fromList :: Parse t a -> Parse t [a]
  29. fromList p (s ::: ss) = (:) <$> p s <*> fromList p ss
  30. fromList p Nil = pure []
  31. fromList _ sx = fail ("Expected list")
  32. gatherList :: S t -> Either String [S t]
  33. gatherList (x ::: xs) = (:) <$> pure x <*> gatherList xs
  34. gatherList Nil = pure []
  35. gatherList sx = fail ("Expected list")
  36. asPair :: ((S t, S t) -> Either String a) -> S t -> Either String a
  37. asPair f (l ::: r ::: SNil) = f (l, r)
  38. asPair _ sx = fail ("Expected two-element list")
  39. asList :: ([S t] -> Either String a) -> S t -> Either String a
  40. asList f ls = gatherList ls >>= f
  41. asSymbol :: (t -> Either String a) -> S t -> Either String a
  42. asSymbol f (A s) = f s
  43. asSymbol _ sx = fail ("Expected symbol")
  44. asAssoc :: ([(S t, S t)] -> Either String a) -> S t -> Either String a
  45. asAssoc f ss = gatherList ss >>= mapM go >>= f
  46. where go (a ::: b ::: Nil) = return (a, b)
  47. go sx = fail ("Expected two-element list")