Rich.hs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. {-# LANGUAGE PatternSynonyms #-}
  2. module Data.SCargot.Repr.Rich
  3. ( -- * 'RichSExpr' representation
  4. R.RichSExpr(..)
  5. , R.toRich
  6. , R.fromRich
  7. -- * Useful pattern synonyms
  8. , pattern (:::)
  9. , pattern A
  10. , pattern L
  11. , pattern DL
  12. , pattern Nil
  13. -- * Useful processing functions
  14. , fromPair
  15. , fromList
  16. ) where
  17. import Control.Applicative ((<$>), (<*>), pure)
  18. import Data.SCargot.Repr as R
  19. -- | A shorter infix alias to grab the head
  20. -- and tail of an `RSList`.
  21. pattern x ::: xs = R.RSList (x : xs)
  22. -- | A shorter alias for `RSAtom`
  23. pattern A a = R.RSAtom a
  24. -- | A shorter alias for `RSList`
  25. pattern L xs = R.RSList xs
  26. -- | A shorter alias for `RSDotted`
  27. pattern DL xs x = R.RSDotted xs x
  28. -- | A shorter alias for `RSList []`
  29. pattern Nil = R.RSList []
  30. type S t = R.RichSExpr t
  31. type Parse t a = S t -> Either String a
  32. -- | Utility function for parsing a pair of things.
  33. fromPair :: Parse t a -> Parse t b -> Parse t (a, b)
  34. fromPair pl pr = asPair $ \(l,r) -> (,) <$> pl l <*> pr r
  35. -- | Utility function for parsing a list of things.
  36. fromList :: Parse t a -> Parse t [a]
  37. fromList p = asList $ \ss -> mapM p ss
  38. asPair :: ((S t, S t) -> Either String a) -> S t -> Either String a
  39. asPair f (L [l, r]) = f (l, r)
  40. asPair _ sx = fail ("Expected two-element list")
  41. asList :: ([S t] -> Either String a) -> S t -> Either String a
  42. asList f (L ls) = f ls
  43. asList _ sx = fail ("Expected list")
  44. asSymbol :: (t -> Either String a) -> S t -> Either String a
  45. asSymbol f (A s) = f s
  46. asSymbol _ sx = fail ("Expected symbol")
  47. asAssoc :: ([(S t, S t)] -> Either String a) -> S t -> Either String a
  48. asAssoc f (L ss) = gatherPairs ss >>= f
  49. where gatherPairs (L [a, b] : ss) = (:) <$> pure (a, b) <*> gatherPairs ss
  50. gatherPairs [] = pure []
  51. gatherPairs _ = fail "..."
  52. asAssoc _ sx = fail ("Expected assoc list")