我已经看到了Python的这个问题,但我对SML(PolyMl)也有同样的问题。
我想创建一个函数,从元组列表(int, string)
中提取最小int
元组的字符串值。
例如,如果我有这个清单:
l = [('a', 5), ('b', 3), ('c', 1), ('d', 6)]
输出应为'c'
,因为最小整数位于元组('c', 1)
中。谢谢!
答案 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 *)