Quasiquotation as described in haskellwiki is shown mostly as useful tool for embedding other languages inside Haskell without messing around with string quotation.
Question is: For Haskell itself, how easy it would be to put existing Haskell code through a quasiquoter for the purpose of just replacing tokens and passing the result over to ghc? Perhaps Template Haskell is key here?
I have looked for code examples and didn’t find any. Some EDSLs can benefit from this ability by reducing the size of their combinating operators (e.g. turn ‘a .|. b .>>. c’ to ‘[myedsl|a | b >> c]’).
You can build quasi-quoters that manipulate Haskell code by, for example, using the haskell-src-meta package. It parses valid Haskell code into an AST, which you can then modify.
In this case, the easiest way to modify the AST is by using Data.Generics to apply a generic transformation to the whole AST that replaces operators with other operators.
We’ll begin by building the transformation function for generic Haskell expressions. The data type that represents an expression is Exp in the template-haskell package.
For example, to convert the operator
>>to.>>.we’d use a function likeThis changes a variable expression (
VarE), but cannot do anything to any other kind of expressions.Now, to walk the whole AST and to replace all occurrences of
>>we’ll use the functionseverywhereandmkTfromData.Generic.In order to make several replacements, we can alter the function so that it takes an association list of any operator to replace.
And by the way, this is a good example of a function that is much nicer to write by using the view patterns language extension.
Now all that’s left for us to do is to build the “myedsl” quasi-quoter.
If you save the above to its own module (e.g.
MyEDSL.hs), then you can import it and use the quasi-quoter.Note that I’ve used
||instead of|because the latter is not a valid operator in Haskell (since it’s the syntactic element used for pattern guards).