【问题标题】:Get min/max int in a list of tuples of (int, string) in PolyML在 PolyML 中 (int, string) 的元组列表中获取最小/最大 int
【发布时间】:2015-04-19 00:49:54
【问题描述】:

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

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

例如,如果我有这个列表:

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

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

【问题讨论】:

    标签: sml ml polyml


    【解决方案1】:
    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 *)
    

    【讨论】:

      【解决方案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
      

      【讨论】:

        猜你喜欢
        • 2015-03-07
        • 2022-01-16
        • 1970-01-01
        • 2020-05-19
        • 1970-01-01
        • 1970-01-01
        • 2012-09-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多