[Haskell-cafe] Expression dye

Andrew Coppin andrewcoppin at btinternet.com
Wed Jul 14 17:37:22 EDT 2010


I'm trying to write a function that builds a series of results in a very 
complicated way. Eventually I ended up writing things like

 > newtype Dye = Dye String deriving (Eq, Show)
 >
 > instance Num Dye where
 >   (Dye x) + (Dye y) = Dye (x ++ " + " ++ y)
 >   (Dye x) - (Dye y) = Dye (x ++ " - " ++ y)
 >   (Dye x) * (Dye y) = Dye (x ++ " * " ++ y)
 >   abs (Dye x) = Dye ("abs " ++ x)

and so on. In this way, you can do something like

 > sum [Dye "x", Dye "y", Dye"z"]

and get "0 + x + y + z" as the result. (In reality you probably want to 
keep track of bracketing and so forth.) In this way, you can take 
functions that accept any Num instance and feed the "dye" through them 
to see what they're actually computing on a given run.

Has anybody ever put anything like this on Hackage? I'd prefer to not 
invent this stuff if somebody has already done it...

(The small problem with the approach above, of course, is that as soon 
as the function wants to do comparisons or take flow control decisions, 
you've got trouble. It's not impossible to solve, but it *is* a lot of 
work...)



More information about the Haskell-Cafe mailing list