作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我知道如何编写代码来查看我的列表是否从小到大排序
isSorted :: (Ord a) => [a] -> Bool
isSorted [] = True
isSorted [x] = True
isSorted (x:y:xs) = x <= y && isSorted (y:xs)
但是我想写一个代码来告诉我我的列表是否按给定的比较运算符排序例如我想加入
sorted (<=) [1,2,2,4,5] == True
sorted (<) [1,2,2,4,5] == False
sorted (==) [1,2,2,2,3] == False
我需要做什么?
最佳答案
I would like to write a code that tells me if my list is sorted by the given comparison operator for example I wanna put in
isSorted
可以增强函数以接收函数,该函数比较两个元素并且可以调用该函数而不是 <=
在你的例子中:
isSorted :: (a -> a -> Bool) -> [a] -> Bool
isSorted _ [] = True
isSorted _ [x] = True
isSorted comparator (x:y:xs) = comparator x y && isSorted comparator (y:xs)
所以函数将被调用为:
isSorted (<) [1, 2, 3]
isSorted (>=) [3, 2, 1]
用 (==)
调用它只会比较列表中的元素是否相同。
关于sorting - 我想检查比较运算符是真还是假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51697602/
我是一名优秀的程序员,十分优秀!