我是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 let“而不是let/ in /end,因此它将递归地调用列表中的其余元组。我的问题是,我不知道如何去做,因为如果我使用if / the,那么我就不能在函数中声明一些值。我很感激任何建议或暗示。
谢谢。
发布于 2017-10-08 16:18:07
您可以从一个函数member (x, xs)开始,如果x是list 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)使用高阶列表组合器map和filter的较短版本
fun find (x, ts) = map #1 (filter (fn (i,j,xs) => member (x, xs)) ts)发布于 2017-10-08 16:20:36
下面是我的实现,并做了一些细微的更改:
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 listhttps://stackoverflow.com/questions/46627597
复制相似问题