首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PolyML -递归列表排序

PolyML -递归列表排序
EN

Stack Overflow用户
提问于 2019-07-23 15:51:50
回答 1查看 45关注 0票数 0

我正在尝试检查PolyML中是否对列表进行了排序。该列表不是内置类型,但我将其定义为:

代码语言:javascript
复制
datatype list = empty | cons of int*list; 

我不知道如何同时检查升序和降序,所以现在我将自己限制在升序(欢迎提供更通用解决方案的任何提示!)。

因此,我的方法如下:

代码语言:javascript
复制
local
    fun sortedIncreasing (empty) = 1000
    |   sortedIncreasing (cons(v,l)) = if(v < sortedIncreasing(l)) then v else Int.minInt
in
    fun isSortedInc (empty) = true
    |   isSortedInc (cons(v,l)) = if (sortedIncreasing(cons(v,l)) = Int.minInt) then false else true
end;   

首先,Int.minInt不是Int类型,所以我有一个类型不匹配。我该怎么解决这个问题呢?

其次,我担心这种方法太幼稚了,我该如何更好地解决这个问题呢?

感谢您的宝贵时间,祝您有愉快的一天!

EN

回答 1

Stack Overflow用户

发布于 2019-11-11 22:22:59

这个问题可以使用一种更通用的方法来解决,通过这种方法,sorted函数接受一个比较器作为参数。

其可能的实现可能如下所示:

代码语言:javascript
复制
fun sorted comp empty = true
  | sorted comp (cons(x,empty)) = true
  | sorted comp (cons(x,cons(y,xs))) =
        (comp (x,y)) andalso (sorted comp (cons(y,xs)));

通过这种方式,您可以检查列表是否按照比较器定义的任意顺序排序。例如,您可以将函数sortedIncreasing定义为:

代码语言:javascript
复制
val sortedIncreasing = sorted op<=;

下面是一个完整的可运行示例来演示这一点:

代码语言:javascript
复制
datatype mylist = empty | cons of int * mylist;

fun sorted comp empty = true
  | sorted comp (cons(x,empty)) = true
  | sorted comp (cons(x,cons(y,xs))) =
        (comp (x,y)) andalso (sorted comp (cons(y,xs)));

fun fromList [] = empty
  | fromList (x::xs) = cons(x, fromList xs);

val a = fromList [1,2,3,4,5,6];
val b = fromList [6,5,4,3,2,1];
val c = fromList [1,3,2,4,5,6];

val sortedIncreasing = sorted op<=;
val sortedDecreasing = sorted op>=;

sortedIncreasing a; (* val it = true: bool *)
sortedDecreasing a; (* val it = false: bool *)
sortedIncreasing b; (* val it = false: bool *)
sortedDecreasing b; (* val it = true: bool *)
sortedIncreasing c; (* val it = false: bool *)
sortedDecreasing c; (* val it = false: bool *)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57159237

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档