Reputation: 1923
I am still learning Haskell and the question seems very basic but it's been stomping me for a while.
Given the following
data Term =
Number Integer
| Abs Term
| Plus Term Term
| Mult Term Term
deriving (Eq, Show)
I want to create an interpreter such that if I call, for example,
evaluate (Plus (Number 10) (Number 10))
it will return 20. Below is what I have so far
myabsolute :: Integer -> Integer
myabsolute n = if n >= 0 then n else -n
evaluate :: Term -> Integer
evaluate Plus = evaluate(t1) + evaluate(t2)
evaluate Mult = evaluate(t1) * evaluate(t2)
evaluate Abs = myabs(evaluate(t1))
evaluate _ = 0
I am confused how to get the Number Integer
part working since I do not know how to extract the numbers and map them to t1
and t2
in Plus
, Mult
, and Abs
.
Since I am still learning, if I am doing something completely wrong please let me know!
Upvotes: 2
Views: 115
Reputation: 52057
Here's how the Plus
case would work:
evaluate :: Term -> Integer
evaluate (Plus t1 t2) = evaluate t1 + evaluate t2
...
The Plus
constructor has two terms, so we need two names in the pattern (t1
and t2
). In this case both t1
and t2
will be values of type Term
which is why the expressions evaluate t1
and evaluate t2
make sense.
The Number
constructor, however, only has one parameter, e.g. Number 3
, so its case will look like:
evaluate (Number x) = ...use x here...
Here the variable x
will have type Integer
.
Upvotes: 7