1 Jul 2005 12:06
best way to do generic programming?
Arka al Eel <arkaaleel <at> gmail.com>
2005-07-01 10:06:05 GMT
2005-07-01 10:06:05 GMT
Hi, I'm playing with generic programming. At the moment I'm interested in reusable transformations on data types. Provided for example a toy datatype Expr like this: data Expr = Const Int | Var String | Add Expr Expr Plus a function "optimize" that optimizes a pattern "x + 0" into "x": optimize (Add x (Const 0)) = x You would now want this to be this generic, so the function should be recursive for all other constructors *and* other data types. For example, suppose that Expr is included in other datatype: data Stm = Assign String Expr | Seq Stm Stm I now want the "optimize" transformation to work on Stm, like this: x = optimize (Seq (Assign (Add (Var "x") (Const 0))) blah blah) For sure, I don't want to write specific code for type Stm. The thing I want is to generically walk through values of those types into Expr where it can apply the pattern. Haskell does not seem to have an easy way to do this. After looking through some papers I found lots of things that *might* handle this, like Generic Haskell, "scrap your boilerplate", Drift, etc. Now I'm(Continue reading)
---------------------------------------------
module Optimize where
import GH.Library.Map
data Expr = Const Int | Var String | Add Expr Expr deriving Show
data Stm = Assign String Expr | Seq Stm Stm deriving Show
stmt :: Stm
stmt = Seq (Assign "y" (Add (Var "x") (Const 0)))
(Assign "z" (Add (Const 0) (Var "y")))
optimize {| t :: * |} :: (optimize{|t|}) => t -> t
optimize extends gmap
optimize {|Expr|} e =
case e of
Add x (Const 0) -> x
Add (Const 0) x -> x
e' -> e'
RSS Feed