1

I was writing my own haskell datatype to resolve a sum operation with integers, but i dont know how to make the semantic .

data Expr = Value Int
    | Sum Expr Expr

I was trying to do:

sum:: Expr -> Expr -> Int
sum a b = b + a
val:: Int -> Int
val a = a

I want to write like:

Sum (Value 3) (Value 5)

And get 8 as return, any ideas?

2
  • What happened when you tried? Commented Oct 16, 2017 at 13:48
  • 1
    Sum (Value 3) (Value 5) will always, by definition, be a distinct value of type Expr; you can't reduce it to 8, because 8 is not a constructor for Expr. Commented Oct 16, 2017 at 13:55

2 Answers 2

4

Typically, in this sort of situation, you write an "evaluator" or "interpreter" -- a single function that accepts an Expr and evaluates it to a value:

eval :: Expr -> Int

Then, you can write:

> eval (Sum (Value 3) (Value 5))
8
>

Haskell's pattern matching for function definitions makes this very elegant:

eval (Value x) = ...
eval (Sum e1 e2) = ...you'll need to use eval recursively here...

So, instead of writing multiple functions, one for each component of your Expr, you write a single function with one pattern-based definition for each component.

If this was homework, you might want to stop here and try to figure the details out for yourself. If it wasn't, then the following should work:

eval :: Expr -> Int
eval (Value x) = x
eval (Sum e1 e2) = eval e1 + eval e2
Sign up to request clarification or add additional context in comments.

Comments

0

You need to define sum appropriately for each combination of data constructors.

sum :: Expr -> Expr -> Int
sum (Value x) (Value y) = x + y
sum (Sum a b) (Sum c d) = sum a b + sum c d
sum (Value x) (Sub a b) = x + sum a b
sum (Sum a b) (Value y) = sum a b + y

This can be simplified; one way is with a helper function that reduces a single Expr to an integer value first.

value :: Expr -> Int
value (Value x) = x
value (Sum x y) = (value x) + (value y)

sum :: Expr -> Expr -> Int
sum x y = value x + value y    

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.