Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 用于检查整数列表的Haskell自定义排序函数_List_Function_Haskell_Recursion - Fatal编程技术网

List 用于检查整数列表的Haskell自定义排序函数

List 用于检查整数列表的Haskell自定义排序函数,list,function,haskell,recursion,List,Function,Haskell,Recursion,我正在尝试编写一个Haskell函数来检查整数列表是否有序,而不使用任何现有函数来排序或检查列表的顺序。我已经写了下面的代码,但我不明白为什么它不工作。我得到一个错误: No instance for (Ord integer) arising from a use of `<=' In the expression: x <= (head xs) 我不明白这是什么意思。是否有其他方法可以编写此函数?这是到目前为止我的代码 isordered :: [integ

我正在尝试编写一个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中,类型名称以大写字母开头,类型变量以小写字母开头。所以如果你写整数,那就是一个类型变量。因此,您的类型与[a]->Bool相同,即您获取任何内容的列表并返回Bool。因此,由于对列表中的项目类型没有限制,因此不允许使用[a]->Bool。后者将使您的函数与实现Ord typeclass的任何类型一起工作,Ord typeclass提供比较运算符,如Haskell中的,类型名称以大写字母开头,类型变量以小写字母开头。所以如果你写整数,那就是一个类型变量。因此,您的类型与[a]->Bool相同,即您获取任何内容的列表并返回Bool。因此,由于对列表中的项目类型没有限制,因此不允许使用[a]->Bool。后者将使您的函数与实现Ord typeclass的任何类型一起工作,该类提供比较运算符,例如什么确切地算作已经存在的函数

isordered xs = all (uncurry (<=)) $ zip xs (tail xs)
更低级的是

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

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

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

使用防护装置的另一种方法:

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

它应该是整数,而不是整数。它应该是整数,而不是整数。任何涉及排序或排序的现有库函数都应该说得更好!在更低级的函数中,它不会总是返回真值吗?我会这样写:isOrdered xs=和$zipWith@chefburns:No,但请尝试一下。@Felix:我想你可以用drop 1 xs替换尾部xs,以保存为空列表。没有尝试过,尽管任何涉及排序或排序的现有库函数都是一个更好的说法!在更低级的函数中,它不会总是返回true吗?我会这样写:isOrdered xs=和$zipWith@chefburns:No,但请尝试一下。@Felix:我认为您可以用drop 1 xs替换尾部xs,以使其保存为空列表,但没有尝试