在方案中将函数作为参数传递
Passing a function as an parameter in scheme
我正在尝试创建一个函数(last),它接受一个函数 ( f ) 和一个 List 作为参数。该列表被传递给函数(奇数?),如果列表中的最后一个元素是奇数,则它 returns true(#t) 否则它 returns false (#f) 。但是下面的代码是不工作,将函数声明为参数的正确方法是什么。
(define (last f L)
(if (null? L) '() ( last f (cdr L)) ))
(last odd? '( 0 5 3 8 6 7))
对于函数的编写方式,您在调用中设置了额外的括号。它应该只是 (last odd? '(0 5 3 8 6 7))
正如有人在评论中建议的那样。
此处介绍了如何仅使用内置函数编写解决方案,注意将过程作为参数传递的正确语法,还要注意将函数命名为 last
, 它与现有的程序冲突,你应该使用相同的程序来解决问题![=14=]
(define (my-last f L)
(f (last L)))
如果您确实必须从头开始编写函数,请确保您了解需要哪些基本情况:
(define (my-last f L)
(cond ((null? L) #f)
((null? (cdr L)) (f (car L)))
(else (my-last f (cdr L)))))
无论哪种方式,它都按预期工作:
(my-last odd? '(0 5 3 8 6 7))
=> #t
我正在尝试创建一个函数(last),它接受一个函数 ( f ) 和一个 List 作为参数。该列表被传递给函数(奇数?),如果列表中的最后一个元素是奇数,则它 returns true(#t) 否则它 returns false (#f) 。但是下面的代码是不工作,将函数声明为参数的正确方法是什么。
(define (last f L)
(if (null? L) '() ( last f (cdr L)) ))
(last odd? '( 0 5 3 8 6 7))
对于函数的编写方式,您在调用中设置了额外的括号。它应该只是 (last odd? '(0 5 3 8 6 7))
正如有人在评论中建议的那样。
此处介绍了如何仅使用内置函数编写解决方案,注意将过程作为参数传递的正确语法,还要注意将函数命名为 last
, 它与现有的程序冲突,你应该使用相同的程序来解决问题![=14=]
(define (my-last f L)
(f (last L)))
如果您确实必须从头开始编写函数,请确保您了解需要哪些基本情况:
(define (my-last f L)
(cond ((null? L) #f)
((null? (cdr L)) (f (car L)))
(else (my-last f (cdr L)))))
无论哪种方式,它都按预期工作:
(my-last odd? '(0 5 3 8 6 7))
=> #t