Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile time code rewriting outside of template haskell scope?

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

like image 770
ghorn Avatar asked Jan 16 '23 15:01

ghorn


1 Answers

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.

like image 99
luqui Avatar answered Feb 01 '23 09:02

luqui