Haskell:'Num [a] =>'之间的区别是什么? a`和`Num a =>并[a]` [英] Haskell: What is the differrence between `Num [a] => a` and `Num a => [a]`
问题描述
elemNum ::(等式,数字b)=> a - > [a] - > b
elemNum e l = f e l
其中f _ [] = [] - 这是我的错字,应该读为0
f e(x:xs)
| x == e = 1 + f e xs
|否则= f e xs
由于上述原因,它显然不起作用。但是,如果我删除我的签名它编译(不知道为什么,请解释),我得到这个签名:
elemNum: :(Num [a],Eq t)=> t - > [t] - > [a]
我从来没有见过类型类 Num [a]
before ..这是什么意思,它与(Num a)=>相比如何? [a]
。
Num a
表示类型 a
可以被视为一个数字;例如。您可以将两个 a
s一起添加以获得新的 a
,或者您可以否定 a
并获得 a
。 整数
和 Double
属于此类别。
相应地, Num [a]
表示类型 [a]
可以被视为一个数字。即您可以将 a
两个列表添加到一起以获取 a
的新列表。这不太可能是有意义的,因为没有列表是数字(默认情况下)。这意味着你正在处理一个列表,就像它是一个数字一样,导致GHC得出结论,你必须让你的列表像一个数字一样行动,从而增加一个适当的约束。
这样的约束可能来自以下函数:
foo (x:xs)= xs + 1
xs
模式匹配作为列表的尾部,因此它本身就是一个列表,然后您将它添加到列表中,将列表视为数字。
Apparently, my type signature was off. I've since found out why. Now, I'm interested in knowing more about the GHCI inferred signature on my typo. I was trying to get this code to work:
elemNum :: (Eq a, Num b) => a -> [a] -> b
elemNum e l = f e l
where f _ [] = [] -- this was my typo, supposed to read 0
f e (x:xs)
| x == e = 1 + f e xs
| otherwise = f e xs
It obviously doesn't work for the reason noted above; but, if I remove my signature it compiles (not sure why, please explain), and I get this signature:
elemNum :: (Num [a], Eq t) => t -> [t] -> [a]
I've never seen the typeclass Num [a]
before.. What does that mean, and how does it compare to (Num a) => [a]
.
Num a
means that the type a
can be treated as a number; eg. you can add two a
s together to get a new a
or you can negate an a
and get an a
. Integer
and Double
fall into this category.
Correspondingly, Num [a]
means that the type [a]
can be treated as a number. I.e. you can add together two lists of a
to get a new list of a
. This is very unlikely to be meaningful because no lists are numbers (by default). It means that you are treating a list like it is a number, causing GHC to conclude that you must want your list to act like a number, and thus adding an appropriate constraint.
Such a constraint might arise from a function like:
foo (x:xs) = xs + 1
xs
is pattern matched as the tail of a list, and thus is itself a list, and then you are adding to it, treating the list as a number.
这篇关于Haskell:'Num [a] =>'之间的区别是什么? a`和`Num a =>并[a]`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!