gpt4 book ai didi

sorting - 我想检查比较运算符是真还是假

转载 作者:行者123 更新时间:2023-12-02 17:06:15 25 4
gpt4 key购买 nike

所以我知道如何编写代码来查看我的列表是否从小到大排序

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com