sml - Custom comparator sort in SML?
问题描述
I am a bit stuck with this problem in SML / SMLNJ and I would love some guidance. So I have a problem where I need to make a function called insertSorted, where it takes a number, a comparison statement, and an (assumed sorted) list that it needs to insert into. I'm not sure how to start approaching this so any help would be amazing.
My thought is to split the two lists up where the number would be, insert the number, and then concatenate both lists.
fun insertSorted (x, comp, []) = [x]
| insertSorted (x, comp, a::rest) = ...
Update: I got a bit farther now I just need to know how to debug this, any guidance?
fun insertSorted (x, []) = [x]
| insertSorted (x, y::ys) =
if (x < y)
then x::y::ys
else if (x > y)
then y::x::ys
else y::insertSorted (x, ys);
Update 2: My new goal is to figure out how to merge these two functions into one. Ultimately named insertSorted.
fun insertSorted (x, nil) = [x]
| insertSorted (x,y::ys) = if x<y then x::y::ys else y :: insertSorted (x,ys);
fun insertSorted (x, nil) = [x]
| insertSorted (x,y::ys) = if x>y then y::x::ys else y :: insertSorted (x,ys);
解决方案
有以下三种情况:
- 名单是
nil
。- 你已经涵盖了这一点。:-)
- 列表不是
nil
,它的第一个元素是小于x
,所以我们需要不断寻找插入的位置x
。- 在这种情况下,结果应该是第一个元素,然后是插入
x
到列表其余部分的结果。
- 在这种情况下,结果应该是第一个元素,然后是插入
- 列表不是
nil
,并且它的第一个元素大于或等于,所以我们可以在这里x
插入。x
- 在这种情况下,结果应该是
x
,后跟整个列表。
- 在这种情况下,结果应该是
区分案例#2 和# 3涉及if
// then
; else
实施案例#2 涉及递归。
推荐阅读
- r - 因素的崩溃
- javascript - 使用数组的索引在该数组的过滤版本中查找相应的索引
- java - jFormatted 文本字段未正确格式化双精度数据
- http-live-streaming - hls 视频:为什么片段长度和目标持续时间之间存在差异?
- python - 将模型保存在单独的线程中
- xamarin.forms - Xamarin UITest 后门可以在 iOS 上返回值吗?
- python - 在其他人代码中对 numpy 数组进行操作
- r - 与上限函数的不一致
- asp.net - 某些下载的 PDF 会导致上传错误 ASP.net
- android - Agora React-Native No Video Feed (Audio Only) 在较新的 Android 设备上部署的应用程序(是 S10,Pixel 3)