简体   繁体   English

编号列表的类型声明

[英]Type Declaration For List of Num

I'm new to Haskell and I have no idea what I'm doing wrong here. 我是Haskell的新手,我不知道自己在做什么错。 The following code generates an error. 以下代码生成错误。

numOfPos :: Num a => [a] -> Int
numOfPos xs = length [x | x <- xs, x > 0]

The code just returns the number of positive elements in the list. 该代码仅返回列表中正数的数量。 The list can contain any type of number. 该列表可以包含任何类型的数字。

The error says "Could not deduce (Ord a) arising from a use of '<' from the context (Num a)..." 错误显示“无法从上下文(数字a)中推断出使用'<”引起的(Ord a)...”

What is the type declaration supposed to be to allow for this function? 应该允许该功能的类型声明是什么?

(>) is defined on the Ord typeclass , not the Num typeclass, so you need to put both the Num and Ord constraints on a for this to work: (>)是在Ord类型类上定义的 ,而不是在Num类型类上定义的,因此您需要同时将NumOrd约束都放在a才能使其起作用:

numOfPos :: (Num a, Ord a) => [a] -> Int
numOfPos xs = length [x | x <- xs, x > 0]

For more information about why elements of Num ("numbers") aren't elements of Ord ("objects that have an ordering"), see this question . 有关为何Num (“数字”)元素不是Ord (“有序对象”)元素的更多信息,请参见此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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