在PolyML中的(int,string)元组列表中获取min / max int

时间:2015-02-18 05:21:00

标签: sml ml polyml

我已经看到了Python的这个问题,但我对SML(PolyMl)也有同样的问题。

我想创建一个函数,从元组列表(int, string)中提取最小int元组的字符串值。

例如,如果我有这个清单:

l = [('a', 5), ('b', 3), ('c', 1), ('d', 6)]

输出应为'c',因为最小整数位于元组('c', 1)中。谢谢!

2 个答案:

答案 0 :(得分:2)

val l = [(#"a", 5), (#"b", 3), (#"c", 1), (#"d", 6)]

fun min [] = NONE
  | min [x] = SOME x
  | min ((c1,n1) :: (c2,n2) :: xs) = if n1 < n2 then
                                       min ((c1,n1) :: xs) 
                                     else
                                       min ((c2,n2) :: xs)

val SOME (c,_) = min l

答案 1 :(得分:0)

val lst = [(#"a", 5), (#"b", 3), (#"c", 1), (#"d", 6)];

(* The first item of a tuple is fetched with #1. *)
#1(List.foldl
    (fn ((new as (_,n)), (old as (_,n0))) =>
      if n < n0 then new else old)
    (hd lst)
    (tl lst));

(* val it = #"c" : char *)