简体   繁体   English

Haskell 多态型

[英]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) == 3eval (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的定义, xy都具有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 :我们知道我们可以使用evalExpr中获取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来评估xy以获得它们的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.

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