[英]How I can solve this : One :: Num a => a -> Bool -> a in Haskell?
Define functions that have the following type signature!定义具有以下类型签名的函数!
One :: Num a => a -> Bool -> a
One = ?
I do not understand how a Num can be a bool and become again a Num.我不明白 Num 怎么可以是 bool 并再次变成 Num。 Could anybody help for me to understand and solve it.任何人都可以帮助我理解和解决它。
how a Num can be a bool and become again a Num. Num 如何成为 bool 并再次成为 Num。 Could anybody help for me to understand this.谁能帮助我理解这一点。
Well, this would be the case if the grouping in the type was to the left, like so好吧,如果类型中的分组在左侧,就会出现这种情况,就像这样
one :: Num a => (a -> Bool) -> a
But actually, the grouping is to the right:但实际上,分组在右边:
one :: Num a => a -> (Bool -> a)
So we need to find a way to turn an a
type value into a way to turn a Bool
value to an a
type value.所以我们需要想办法把一个a
类型的值变成一个Bool
值变成a
类型的值。
Since we will have had this a
type value, we could just return it:因为我们将拥有a
类型值,所以我们可以直接返回它:
one a = two
where
two b = a
Do note that I had to change One
to one
.请注意,我必须one
One
更改。 While One
is syntactically a type in Haskell, one
is a value which has a type. One
在句法上是 Haskell 中的一种类型,而one
是具有类型的值。 Which you show.你展示的。
So what we did here is define the value one
, which has this type.所以我们在这里所做的是定义值one
,它具有这种类型。 Or in Haskell,或者在Haskell,
one :: a -> (Bool -> a)
But wait, where did the Num a =>
constraint go?但是等等, Num a =>
constraint go 在哪里? We didn't use it at all, and that's why all we could do was to just return the a
.我们根本没有使用它,这就是为什么我们所能做的就是返回a
。
But what does it mean, for a
to be a Num
?但是a
是Num
是什么意思?
GHCi> :i Num
class Num a where
(+) :: a -> a -> a
(*) :: a -> a -> a
(-) :: a -> a -> a
negate :: a -> a
abs :: a -> a
signum :: a -> a
So then, any Num
has absolute value, and can be negated.那么,任何Num
都是有绝对值的,都可以取反。 Thus a possible definition is因此一个可能的定义是
one :: Num a => a -> (Bool -> a)
one a = two
where
two b | b = negate a
| otherwise = abs a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.