繁体   English   中英

Haskell自定义isordered函数可检查整数列表

[英]Haskell custom isordered function to check a list of integers

我正在尝试编写一个Haskell函数,该函数检查整数列表是否按顺序排列,而无需使用任何现有功能对列表进行排序或检查。 我已经编写了以下代码,但是我不明白为什么它不起作用。 我得到错误:

No instance for (Ord integer)
      arising from a use of `<='
    In the expression: x <= (head xs)

我不明白这是什么意思。 我应该以其他方式编写此函数吗? 到目前为止,这是我的代码。

isordered :: [integer] -> Bool
isordered [] = True
isordered (x:[]) = True
isordered (x:xs)|x <= (head xs) = isordered xs
                |otherwise = False

提前致谢!!!

在Haskell中,类型名称以大写字母开头,类型变量以小写字母开头。 因此,如果您写integer ,那是一个类型变量。 因此,您的类型与[a] -> Bool ,即,您获取所有内容的列表并返回Bool。 因此,由于对列表中可能包含的项目类型没有任何限制,因此不允许在其上使用<=

要解决此问题,您可以将其更改为Integer ,这就是您想要的,或者添加如下Ord约束: Ord a => [a] -> Bool 后者将使您的函数可以与实现Ord typeclass的任何类型一起使用(该类型提供了比较运算符,例如<= )。

什么才算是“已经存在的功能”?

isordered xs = all (uncurry (<=)) $ zip xs (tail xs)

更底层的是

isordered (x:y:zs) = x <= y && isordered (y:zs)
isordered _ = True 

使用防护的另一种方法是:

isOrdered :: Ord a => [a] -> Bool
isOrdered (x:y:xs) | x<=y = isOrdered (y:xs)
                   | otherwise = False
isOrdered _ = True

暂无
暂无

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

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