标准ML:迭代列表时检查条件

问题描述 投票:0回答:1

我正在研究编程语言标准ML,我想知道我如何迭代一个带有检查条件的列表。

在其他语言中,我们有如下循环:

var input;
for(var i = 0; i < arr.length; i++) {
   if(arr[i] == input) {
      //you have arrived at your condition...
   } else {
     //other case
   }
}

f.ex

我想迭代列表并检查输入变量是否与列表中的现有元素匹配。

i = 5  
xs = [1,5,2,3,6] --> the element matches after one iteration.

fun check i nil = []
| check i (x::xs) = if i=x 
                    then //dowork 
                    else //iterate;

我已经阅读了许多关于如何实现这一点而没有成功的文档。

如果有人可以给我一些解释,如果我可以在这种工作条件的内部或外部使用let val A in B end;,那将是非常有帮助的。

functional-programming sml
1个回答
0
投票

我如何迭代一个带有检查条件的列表

fun check i nil = []
| check i (x::xs) = if i=x 
                    then //dowork 
                    else //iterate;

我想迭代列表并检查输入变量是否与列表中的现有元素匹配。

我称之为谓词组合子。它已经存在于标准库中,称为List.exists。但你也可以自己做:

fun exists p [] = false
  | exists p (x::xs) = p x orelse exists p xs

这是你正在尝试的if-then-else的简化,它看起来像:

fun exists p [] = false
  | exists p (x::xs) = if p x then true else exists p xs

当结果类型是布尔值时,if-then-else不是必需的,因为orelseandalsonot是短路的(如果结果可以用第一个确定,则不会评估它们的第二个操作数)。

使用此List.exists函数检查列表是否包含特定元素,您必须构造一个p,将list元素与某个给定值进行比较,例如:

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

这似乎比简单地从头开始递写check更复杂,

fun check y [] = false
  | check y (x::xs) = ... orelse check y xs

但出于若干原因,优选使用高阶函数的解决方案。

一个是经验丰富的读者会在看到List.exists时快速检测到你在做什么:啊,你正在扫描列表中给出一个谓词的元素。如果你的函数是显式递归的,那么读者必须阅读完整的递归方案:好的,该函数没有做任何时髦的事情,如果我看到的话,我已经知道了。 List.exists

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.