Skip to content

Instantly share code, notes, and snippets.

@noughtmare
Last active October 28, 2024 20:17
Show Gist options
  • Save noughtmare/0d922f68c6a02045f9e06d2396540c75 to your computer and use it in GitHub Desktop.
Save noughtmare/0d922f68c6a02045f9e06d2396540c75 to your computer and use it in GitHub Desktop.
Using Template Haskell instead of a parser.
import qualified Language.Haskell.TH.Syntax as TH
data ULC = Var String | Lam String ULC | App ULC ULC deriving (Show, TH.Lift)
quote :: TH.Exp -> Maybe ULC
quote (TH.VarE v) = Just $ Var (TH.nameBase v)
quote (TH.UnboundVarE v) = Just $ Var (TH.nameBase v)
quote (TH.AppE x y) = App <$> quote x <*> quote y
quote (TH.LamE vs x) = foldr (\v xs -> Lam <$> (case v of TH.VarP v' -> Just (TH.nameBase v'); _ -> Nothing) <*> xs) (quote x) vs
quote _ = Nothing
q :: TH.Quote m => m TH.Exp -> m TH.Exp
q x = maybe (error "Unquotable expression") TH.lift . quote =<< x
-- >>> $(q[|\s z -> s (s z)|])
-- Lam "s" (Lam "z" (App (Var "s") (App (Var "s") (Var "z"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment