[Haskell-cafe] Re: "quoting" in Haskell

apfelmus apfelmus at quantentunnel.de
Tue Aug 28 02:43:03 EDT 2007


Peter Verswyvelen wrote:
> In Scheme, on can "quote" code, so that it becomes data. Microsoft's F# 
> and C# 3.0 also have something similar that turns code into "expression 
> trees".
>
> I can't find something similar for Haskell? Maybe I am looking at the 
> wrong places?

Quoting/Inspecting code at runtime is not possible in Haskell since this 
would break referential transparency, i.e. one could tell that two 
extensionally equal values like

   3 `add` 4
   1 `add` (2 `mul` 3)

are different by inspecting their internal structure.

Of course, you can use constructors for  add  and  mul  and then inspect 
and transform the result

   data Expr = Val Int | Add Expr Expr | Mul Expr Expr

   add, mul :: Expr -> Expr -> Expr
   add = Add
   mul = Mul

   x :: Expr
   x = Val 1 `add` (Val 2 `mul` Val 3)

By making  Expr  an instance of the class  Num , you can use overloaded 
arithmetic operations

   instance Num Expr where
     (+) = Add
     (*) = Mul
     fromInteger = Val . fromInteger

   x :: Expr
   x = 1 + 2*3


> I want to write something like
> 
> selectiveQuote [add] (1 `add` 2 `mul` 3)
> 
> which would result in an expression tree like
> 
>   add
>  /      \
> 1        6
> 
> So the `mul` is not quoted because it is not part of the "context" = [add]

I'm not sure why you'd want to do that, but it's not well-defined. What 
would

  selectiveQuote [add] ((1 `add` 2) `mul` 3)

be? How to expand `mul` here when `add` isn't expanded?


Regards,
apfelmus



More information about the Haskell-Cafe mailing list