SML / NJ在列表元组列表中搜索

时间:2017-10-08 04:48:12

标签: sml smlnj

我对SML / NJ很新,我有点迷茫。我一直在尝试实现一个函数来搜索其中包含一些列表的元组列表,例如:

val x = [(5, 2, [9 , 8, 7]), (3, 4, [6, 5, 0]), (11, 12, [8, 3, 1])] 

我希望我的函数在目标编号和元组的元素3中的数字之间匹配时将元组的第一个元素添加到新列表中。我已经尝试了几种实现,但到目前为止它们都没有正常工作。

type id = int* int* int list;
val b:id list = [(5,2,[9,8,7]), (3,4,[6,5,0]), (11, 12, [8,3,1])]
val number: int = 8;
val a: int list = nil;

fun findNum(nil) = a | findNum (x: id list) =
    let val tem = hd(x)
        val theList = #3tem
        val i = #1tem
        fun findMatch(nil) = a | findMatch(tem) =
            if (number = hd(theList)) then i::a 
            else findMatch (tl(theList))
    in findNum(tl(x))
    end;

 findNum(b);

我知道它编写得很糟糕,这就是为什么它不断返回一个空列表。我觉得我需要做“if else”而不是let / in / end,所以它将递归调用列表中的其余元组。我的问题是我不知道该怎么做,因为如果我使用if / else然后我不能在函数内声明一些值。我感谢任何建议或提示。

谢谢。

2 个答案:

答案 0 :(得分:1)

如果member (x, xs)是列表x中的元素,则可以从函数xs开始为真:

fun member (x, xs) = List.exists (fn y => x = y) xs

基本情况是三元组列表为空时。然后x不会出现在任何(不存在的)三元组的第三个元素中,并且结果列表为空。通过对列表的第一个元素进行模式匹配来实现递归案例,该元素是三元组(i,j,xs)和列表的尾部ts,并询问x是否为第三个元素xs的成员;如果是,则返回元组的第一部分i

fun find (x, []) = []
  | find (x, (i,j,xs)::ts) =
    if member (x, xs)
    then i :: find (x, ts)
    else find (x, ts)

使用高阶列表组合器mapfilter的较短版本:

fun find (x, ts) = map #1 (filter (fn (i,j,xs) => member (x, xs)) ts)

答案 1 :(得分:0)

这是我的实现,稍作修改:

type id = int* int* int list;
val b:id list = [(5,2,[9,8,7]), (3,4,[6,5,0]), (11, 12, [8,3,1])]
val number: int = 8;

fun findNum [] = [] 
  | findNum (x::xs)  =
        let 
           val theList :int list = #3 (x :id)
           val i : int = #1 x
           fun findMatch [] = false
             | findMatch (y::ys) = if (number = y) then true
                                   else findMatch ys
        in 
           if (findMatch theList = true) then i ::(findNum xs) 
           else (findNum xs) 
        end;

示例:

- findNum b;
val it = [5,11] : int list
相关问题