SML 函数参数

发布于 2024-12-12 21:37:41 字数 178 浏览 4 评论 0原文

条件:
当1.列表比2.列表长时返回值:1
当 1.list 与 2.list 具有相同数量的元素时 返回值:0 1. 当列表比w短时。列表返回值:~1

([1,2,4,5],[3,2,5]);
1

([1,2],[1,5]);
 0

([5],[8,2,3]);
~1

Condition:
when 1. list was longer than the 2. list Return Value :1
when 1. list had the same number of elements as the 2. list Return Value : 0
when the 1. list was shorter than the w. list Return Value : ~1

([1,2,4,5],[3,2,5]);
1

([1,2],[1,5]);
 0

([5],[8,2,3]);
~1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹏半生如梦愿梦如真 2024-12-19 21:37:41

在这种情况下,length 函数可能是你的朋友:

fun foo (xs, ys) =
    let
      val len_xs = length xs
      val len_ys = length ys
    in
      case (len_xs < len_ys, len_xs > len_ys) of
        (true, false) => ~1
      | (false, true) => 1
      | (false, false) => 0
    end

它将产生结果:

- foo ([1,2,4,5],[3,2,5]);
val it = 1 : int
- foo ([1,2],[1,5]);
val it = 0 : int
- foo ([5],[8,2,3]);
val it = ~1 : int

然而,这既低效又丑陋。因此,我们也可以一次从每个列表中取出一个元素,直到其中一个(或两个)变空:

fun bar ([], []) = 0
  | bar (_, []) = 1
  | bar ([], _) = ~1
  | bar (_ :: xs, _ :: ys) = bar (xs, ys)

这给出了结果:

- bar ([1,2,4,5],[3,2,5]);
val it = 1 : int
- bar ([1,2],[1,5]);
val it = 0 : int
- bar ([5],[8,2,3]);
val it = ~1 : int

Well the length function could be your friend in this case:

fun foo (xs, ys) =
    let
      val len_xs = length xs
      val len_ys = length ys
    in
      case (len_xs < len_ys, len_xs > len_ys) of
        (true, false) => ~1
      | (false, true) => 1
      | (false, false) => 0
    end

which will yield the results:

- foo ([1,2,4,5],[3,2,5]);
val it = 1 : int
- foo ([1,2],[1,5]);
val it = 0 : int
- foo ([5],[8,2,3]);
val it = ~1 : int

However this is both inefficient and ugly. So we can also just pull off one element from each of the list at a time until one of them (or both) gets empty:

fun bar ([], []) = 0
  | bar (_, []) = 1
  | bar ([], _) = ~1
  | bar (_ :: xs, _ :: ys) = bar (xs, ys)

Which gives the results:

- bar ([1,2,4,5],[3,2,5]);
val it = 1 : int
- bar ([1,2],[1,5]);
val it = 0 : int
- bar ([5],[8,2,3]);
val it = ~1 : int
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文