【问题标题】:SML greater of two listsSML 大于两个列表
【发布时间】:2013-12-29 14:14:30
【问题描述】:

在我似乎无法解决的 SML 问题上需要帮助。基本上我有两个列表,我需要从每个列表中返回更大的。

调用示例:

Greater([8,4,12,5,6],[2,6,14,4,5]);

将返回 (8,6,14,6)。

我刚开始使用 SML 中的列表,甚至不知道从哪里开始。

【问题讨论】:

  • 返回值只有四个。返回值应该是(8,6,14,5,6)吗?

标签: function sml smlnj


【解决方案1】:
val greater = List.map Int.max o ListPair.zip

或将其扩展:

fun greater(nil, nil)     = nil
  | greater(x::xs, y::ys) = (if x > y then x else y)::greater(xs, ys)
  | greater(_, _)         = raise Domain

【讨论】:

  • 感谢您的快速回复!无论如何,在功能方面这样做吗?只是想看看这一切是如何崩溃的。从未使用过 ListPair.zip,所以不确定它到底是做什么的。
  • @user3091510,添加了独立的实现。
  • 哦,ListPair.zip 从一对列表中创建了一个对列表。
【解决方案2】:

假设你有两个长度相等的列表,你可以定义这个函数:

fun greater nil nil = nil
  | greater (x::xs) (y::ys) = 
       if x > y then x::(greater xs ys) else y::(greater xs ys);

或者,通过将问题简化为从整数对列表到整数列表的映射:

fun zip nil nil = nil
  | zip (x::xs) (y::ys) = (x,y)::(zip xs ys);

fun max (x,y) = if x > y then x else y;

fun greater xs ys = map max (zip xs ys);

请注意,ML 中的列表表示为 [1,2,3] 而不是 (1,2,3),后者是一个包含三个元素的元组。然后这个函数被称为:

- greater [1,2,3,4] [2,3,4,5];
val it = [2,3,4,5] : int list

- greater [~1,8,3] [8,~1,~2];
val it = [8,8,3] : int list

【讨论】:

    【解决方案3】:

    更好:

    val greater = ListPair.map Int.max
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-08
      • 2014-12-18
      • 2022-07-09
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      相关资源
      最近更新 更多