Reputation: 3068
I have this type recursively:
data Expr = Add Expr Expr | Num Int
add (Add (Num a) (Num b)) = a + b
For add Add ((Num 1) (Num 2))
works, but how can I do for all recursively types, like:
add Add( (Add (Num 1) (Num 2)) (Num 3) ) ?
Upvotes: 3
Views: 570
Reputation: 8755
Since you have no way of knowing just how deep a value of your Expr type nests, you have to write a recursive function to evaluate it rather than trying to take on the entire expression at once.
For your Expr type, it would look something like this:
eval :: Expr -> Int
eval (Add a b) = eval a + eval b
eval (Num a) = a
In general, when you have a recursive type like this, you're going to need a recursive function to do anything really interesting with it.
Upvotes: 7