WellFormed.hs 2.0 KB

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