list - 标准ML : Searching through a list of lists

标签 list functional-programming sml ml

我编写了这个函数来确定给定元素是否存储在元组列表的列表中,但目前它只搜索第一个列表。我将如何搜索其余列表?

fun findItem (name : command, ((x,y)::firstlist)::tail : (command*command) list list) = 
    if x = name then true else findItem(name, firstlist::tail)
    | findItem(name, [[]]) = false 

最佳答案

您将递归列表的其余部分(您需要三种情况):

fun findItem (name, ((x,_)::firstlist)::tail) = x = name orelse findItem(name, firstlist::tail)
  | findItem (name, []::tail) = findItem (name, tail) 
  | findItem(name, []) = false

但是,如果您首先编写一个搜索列表的函数,然后在另一个函数中使用它,那么看起来会更容易:

fun findItemHelper (_, []) = false
  | findItemHelper (name, (n', _)::ns) = name = n' orelse findItemHelper (name, ns)

fun findItem (_, []) = false
  | findItem (name, n::ns) = findItemHelper (name, n) orelse findItem (name, ns)

除了orelse之前的部分之外,它们完全相同,因此我们可以使用谓词函数将其抽象出来:

fun find (_, []) = false
  | find (found, x::xs) = (found x) orelse find (found, xs)

并使用它:

fun findItemHelper (name, ns) = find (fn (n, _) => name = n, ns)

fun findItem (name, nss) = find (fn ns => findItemHelper (name, ns), nss)

关于list - 标准ML : Searching through a list of lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44772260/

相关文章:

python - 如果不在列表中

haskell - 用于进度跟踪的 Monad 转换器

functional-programming - 实现懒惰和内存

python - 列表操作

java - 创建一个列表,添加一个元素并在一条语句中将其返回给调用者

haskell - Haskell 中的 WHNF 减少是否发生在编译时?

sml - 使用前定义类型

data-structures - 权重偏左的堆 : advantages of top-down version of merge?

python - 从 n 个相等的项目中挑选与最小数字相关的项目

recursion - 替换列表中每个出现的元素,仅当它跟在指定元素之后时