标准 ML:迭代列表时检查条件
Standard ML : Check conditions when iterating a list
我正在学习编程语言 Standard ML,我想知道如何使用检查条件迭代列表。
在其他语言中,我们有 for 循环,例如:
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;
我查阅了许多关于如何实现它但没有成功的文档。
如果有人能给我解释一下如何在 if 条件的内部或外部使用 let val A in B end;
进行此类工作,那将非常有帮助。
how i can iterate a list with a check condition
fun check i nil = []
| check i (x::xs) = if i=x
then //dowork
else //iterate;
i want to iterate through a list and check if the input variable matches a existing element in the list.
我将其称为谓词组合器。它已经存在于标准库中并被称为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 并不是必需的,因为 orelse
、andalso
和 not
是短路的(不会评估它们第二个操作数,如果结果可以用第一个来确定)。
使用此 List.exists
函数检查列表是否包含特定元素,您必须构造一个 p
将列表元素与某个给定值进行比较,例如:
fun check y xs = List.exists (fn x => ...) xs
这似乎比简单地从头开始递归地编写 check
更复杂一些,
fun check y [] = false
| check y (x::xs) = ... orelse check y xs
但出于多种原因,首选使用高阶函数的解决方案。
一个是经验丰富的 reader 会在看到 List.exists
时快速检测出您在做什么:啊,您正在扫描列表以查找给定谓词的元素。而如果您的函数是显式递归的,则 reader 将必须读取整个递归方案:好的,该函数不会做任何时髦的事情,如果我看到过例如List.exists
.
我正在学习编程语言 Standard ML,我想知道如何使用检查条件迭代列表。
在其他语言中,我们有 for 循环,例如:
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;
我查阅了许多关于如何实现它但没有成功的文档。
如果有人能给我解释一下如何在 if 条件的内部或外部使用 let val A in B end;
进行此类工作,那将非常有帮助。
how i can iterate a list with a check condition
fun check i nil = [] | check i (x::xs) = if i=x then //dowork else //iterate;
i want to iterate through a list and check if the input variable matches a existing element in the list.
我将其称为谓词组合器。它已经存在于标准库中并被称为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 并不是必需的,因为 orelse
、andalso
和 not
是短路的(不会评估它们第二个操作数,如果结果可以用第一个来确定)。
使用此 List.exists
函数检查列表是否包含特定元素,您必须构造一个 p
将列表元素与某个给定值进行比较,例如:
fun check y xs = List.exists (fn x => ...) xs
这似乎比简单地从头开始递归地编写 check
更复杂一些,
fun check y [] = false
| check y (x::xs) = ... orelse check y xs
但出于多种原因,首选使用高阶函数的解决方案。
一个是经验丰富的 reader 会在看到 List.exists
时快速检测出您在做什么:啊,您正在扫描列表以查找给定谓词的元素。而如果您的函数是显式递归的,则 reader 将必须读取整个递归方案:好的,该函数不会做任何时髦的事情,如果我看到过例如List.exists
.