[英]Haskell polymorphic type
I am working on an excercise but i don't know how to create the division function我正在练习,但我不知道如何创建分区 function
-- 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))
Let's look at the first case:我们来看第一种情况:
eval (Val n) = n
By the definition of Val
, n
is an Int
, so we simply return n
.根据Val
的定义, n
是一个Int
,所以我们简单地返回n
。 Then, for example, eval (Val 3) == 3
, eval (Val 10) == 10
, etc.然后,例如, eval (Val 3) == 3
, eval (Val 10) == 10
等。
Now let's look at the second case.现在让我们看第二种情况。
eval (Div x y) = ???
By the definition of Div
both x
and y
have type Expr
, so we can't simply return one or the other, and we don't know how to do math on Expr
values.根据Div
的定义, x
和y
都具有Expr
类型,因此我们不能简单地返回一个或另一个,而且我们不知道如何对Expr
值进行数学运算。 But we do now how to do math on Int
values:但是我们现在要做的是如何对Int
值进行数学运算:
> 6 `div` 3
2
and we know we can use eval
to get an Int
from an Expr
:我们知道我们可以使用eval
从Expr
中获取Int
:
> eval (Val 6)
6
So the first thing you need to do is use eval
to evaluate both x
and y
to get their Int
values.所以你需要做的第一件事是使用eval
来评估x
和y
以获得它们的Int
值。 Once you have them, you can use div
to produce the desired value.拥有它们后,您可以使用div
生成所需的值。
> eval (Div (Val 6) (Val 3))
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.