Is it possible to create a function which rewrites haskell code at compile time from outside of template haskell quotes?
For example:
differentiate :: Floating a => (a -> a) -> a -> (a,a)
differentiate = -- what goes here?
f :: Num a => a -> a
f = sin
g :: Num a => a -> (a,a)
g = differentiate f
and at compile time it would transform g to:
g x = (sin x, cos x)
I would like my "differentiate" function to be passed the AST of "f" and let me rewrite it before compiling. As far as I'm aware you cannot do this in template haskell without passing it the full syntax of the function i.e. "g = differentiate sin".
Thank you
You are talking about macros as in scheme. The answer is no. Haskell functions must be "referentially transparent", which means if you give it two denotationally equal arguments, the results must be denotationally equal. I.e., every f
must have
f (1 + 1) = f 2
And if f
were a macro this would not necessarily be so. However, this property is essential to the "purity" of the language -- what makes Haskell so nice to reason with and refactor.
However, there is extensive work on automatic differentiation in Haskell, none of which needs a macro system -- abstract modeling (and typeclasses to make it look nice) are all that is necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With