-
Haskell Help
Hi people, i have some haskell problems with expressions. What i am trying to do is add two expressions together and simplify the output. I have this code
Code:
module X where
type Variable = String
data X = Const Integer
| Var Variable
| Plus X X
deriving (Eq, Show)
What i am trying to achieve is when i write for example Plus (Var "x")(Const 0) in Hugs, to get "Var x". The 0 is disregarded as it adds nothing to x (0 + x = x). If the Const is 1 again the output should be "Var x" as 1 + x = x.
Any help is appreciated
Thnx
-
What? Since when does 1 + x = x? :confused: I think the universe would explode or something if that were true. :)
Code:
-- code removed by request
-
thnx for the code i will try it later when i come back home..actually i have done a mistake..not 1+x but rather 1*x = x..i apologize for the confusion :(..
-
But you have no multiplication operator. You'd have to add one:
Code:
-- code removed by request
-
yes i was just giving example with the multiplication to make it clearer..also is there a way to add the 2 Expr together in case they are both Const? example : if we have Plus(Const 2)(Const 5) = 7. What i did was i wrote a separate function
[/CODE]add :: Expr -> Integer
add (Plus (Const x) (Const y)) = x + y[/CODE]
and it works but i was wondering if i can have this in the simplify function? It gives me an error to do with the Type. I have defined simplify to be Expr -> Expr but with the adding i want to get an integer back and thats where the error comes.
-
What we were doing before was merely normalisation; now, you're talking about evaluation. It will work something like this (rather dumb version, I'm afraid):
Code:
-- code removed by request
The error with your original was that you were trying to return an Integer, but the function was meant to return an Expr.
-
Thanks for the code but i think i will just stick to my function. I am pretty bad at haskell and i dont completely understand the code you gave so i rather not use it (in case i get asked questions on it). I will try and do it the way i can and understand it and just keep it as simple as possible even if my program is not going to behave as it is expected.
I have another question concerning converting an expression to string. I had a look on the web and "Show" function is mentioned.I tried it with simple input but i couldnt convert it to string. Anyone could point me to something more useful?
-
You're probably confused by the on function. on is (roughly) defined thusly:
Code:
on :: (b -> b -> b) -> (a -> b)
on g f = \x y -> f x `g` f y
So,
Code:
liftConst = Const . on (fromConst . evaluate)
is the same as (adding in all the points)
Code:
liftConst op a b = Const $ op (fromConst $ evaluate a) (fromConst $ evaluate b)
It's just a little more elegant.
-
do u know why it doesnt let me load the data.function module?
I typed it exactly as posted and it gave me error saying i cant find the module.
-
What compiler and version are you using?