简体   繁体   中英

Haskell - arithmetic operations with datatypes

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?

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

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    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM