【发布时间】:2021-03-23 09:22:26
【问题描述】:
我在 SML / SMLNJ 中遇到了这个问题,我希望得到一些指导。 所以我有一个问题,我需要创建一个名为 insertSorted 的函数,它需要一个数字、一个比较语句和一个需要插入的(假定排序的)列表。我不知道如何着手解决这个问题,所以任何帮助都会很棒。
我的想法是将两个列表拆分到数字所在的位置,插入数字,然后连接两个列表。
fun insertSorted (x, comp, []) = [x]
| insertSorted (x, comp, a::rest) = ...
更新:我现在走得更远了,我只需要知道如何调试它,有什么指导吗?
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);
更新 2:我的新目标是弄清楚如何将这两个函数合并为一个。最终命名为 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);
【问题讨论】: