我需要在let中定义一个函数并能够立即使用它,如下所示:
(let ((test (lambda () (print "ha"))))
(test))
Run Code Online (Sandbox Code Playgroud)
但是,由于test是一个变量(而不是函数),因此它不起作用.相反,我需要像这样运行它:
(let ((test (lambda () (print "ha"))))
(funcall test))
Run Code Online (Sandbox Code Playgroud)
在我的情况下,这是一个问题.我可以通过制作一个更改(测试)到(funcall测试)的宏来解决这个问题,但是,这不起作用,因为宏的名称将与我的情况中的方法相同(我猜这会导致(测试) )成为(funcall test)=>(funcall(funcall test))=> ......?)
有没有办法在lambda中定义一个方法并立即运行它,而不用像funcall这样的东西?
每当第二个数字(在这种情况下为y)为负数时,代码都不会给出答案,并最终崩溃。因此(RecursiveMultiply 9 3),(RecursiveMultiply -9 3)工作,(RecursiveMultiply 9 -3)崩溃,(RecursiveMultiply -9 -3)崩溃。
这是我的代码
(define RecursiveMultiply
(lambda (x y)
(if (= y 1)
x
(+ x (RecursiveMultiply x (- y 1))))))
Run Code Online (Sandbox Code Playgroud) 我一直在尝试编写返回矩阵转置的函数.所以输出的例子就是,(transpose (list '(1 2) '(4 5))) ;==> ((1 4) (2 5)) 这是我的功能:
(define transpose
(lambda (m1)
(if (null? (cadr m1))
null
(list (indiv (car m1) (cadr m1)) (transpose (rest m1))))))
(define indiv
(lambda (l1 l2)
(if (empty? l1)
null
(list (list (car l1) (car l2)) (indiv (rest l1) (rest l2))))))
Run Code Online (Sandbox Code Playgroud)
indiv函数负责行递归,而transpose调用indiv函数来获取转置.我的问题是为什么不能 (if (null? (cadr m1))检查我是否到达了矩阵的最后一行?有没有办法在计划中检查这个?我不想用另一种方法来解决这个问题,我只是想知道这是否可行,如果是,那么如何?
根据我对递归调用的了解,当您通过调用函数递归到该语句时,该语句必须是一个return语句,因为从根本上说,当它从函数堆栈中弹出时,它希望从较早的调用中获得一些值。
我有一些插入BST的代码
insertCorrectLocation(root, newNode) {
if (newNode.data < root.data) {
if (root.left == null) {
root.left = newNode
} else {
return this.insertCorrectLocation(root.left, newNode)
}
}
else {
if (root.right == null) {
root.right = newNode
} else {
return this.insertCorrectLocation(root.right, newNode)
}
}
}
Run Code Online (Sandbox Code Playgroud)
即使我删除了调用的return语句(例如,
else {
if (root.right == null) {
root.right = newNode
} else {
this.insertCorrectLocation(root.right, newNode)
}
}
Run Code Online (Sandbox Code Playgroud)
这是怎么发生的?
方案/球拍中的功能是什么,可用于检查实数是否在给定的数字范围内。
racket ×3
recursion ×3
scheme ×3
algorithm ×1
common-lisp ×1
if-statement ×1
javascript ×1
lambda ×1
lisp ×1
range ×1