简体   繁体   English

SML大于两个列表

[英]SML greater of two lists

Need help with an SML problem I can't seem to solve. 需要SML问题的帮助,我似乎无法解决。 Basically I have two list and I need to return the greater from each list. 基本上我有两个列表,我需要从每个列表中返回更大的列表。

Example call: 示例调用:

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

Would return (8,6,14,6). 将返回(8,6,14,6)。

I just started working with lists in SML and not even sure where to start on this. 我刚刚开始使用SML中的列表,甚至不知道从哪里开始。

val greater = List.map Int.max o ListPair.zip

Or to expand that out: 或将其扩展:

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

Assuming you have two lists of equal lengths you could define this function: 假设您有两个长度相等的列表,则可以定义此函数:

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

Or alternatively, by reducing the problem to a mapping from a list of int pairs to a list of ints: 或者,通过将问题简化为从整数对列表到整数列表的映射:

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);

Note that lists in ML are denoted as [1,2,3] and not (1,2,3) , which is a tuple with three elements. 请注意,ML中的列表表示为[1,2,3]而不是(1,2,3) ,它是具有三个元素的元组。 This function is then called as: 然后将该函数称为:

- 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

甚至更好:

val greater = ListPair.map Int.max

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM