Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 哈斯克尔多态型_Haskell - Fatal编程技术网

Haskell 哈斯克尔多态型

Haskell 哈斯克尔多态型,haskell,Haskell,我正在练习,但我不知道如何创建除法函数 -- defines data type with two constructors data Expr = Val Int | Div Expr Expr -- defines a function that turns an expression into an integer -- eval :: Expr -> Int -- eval (Div x y) = Div x * Div y -- write an evaluation fu

我正在练习,但我不知道如何创建除法函数

-- defines data type with two constructors
data Expr = Val Int | Div Expr Expr

-- defines a function that turns an expression into an integer
-- eval :: Expr -> Int


-- eval (Div x y) = Div x * Div y
-- write an evaluation function for both Expr types
-- TODO eval (Val n) =
eval (Val n) = n


-- TODO eval (Div x y) =



-- now calculate 6 / 3 with the created function
-- TODO testeval =
testeval = eval (Div (Val 6) (Val 3))

让我们来看第一个案例:

eval (Val n) = n
根据
Val
的定义,
n
Int
,因此我们只需返回
n
。然后,例如,
eval(Val 3)==3
eval(Val 10)==10
,等等

现在我们来看第二个案例

eval (Div x y) = ???
根据
Div
的定义,
x
y
都有类型
Expr
,因此我们不能简单地返回其中一个,我们也不知道如何对
Expr
值进行计算。但我们现在要做的是如何计算
Int
值:

> 6 `div` 3
2
我们知道我们可以使用
eval
Expr
获取
Int

> eval (Val 6)
6
因此,您需要做的第一件事是使用
eval
计算
x
y
以获得它们的
Int
值。拥有它们后,可以使用
div
生成所需的值

> eval (Div (Val 6) (Val 3))
2

反复思考
x
y
都是
Expr
类型的值。您是否有类型为
Expr->Int
的函数?给定两个
Int
值,可以将它们除以以获得另一个
Int
?而且,这不涉及多态性。更确切地说,
expr
是一种求和类型,其值被“标记”为
Val
ues或
Div
isions。很抱歉,我还是个新手,搞不懂,似乎无法理解如何访问函数中的值