尾递归映射函数球拍 [英] Tail recursive Map function RACKET
本文介绍了尾递归映射函数球拍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
racket中的map函数接受一个函数和一个列表,并递归地将该函数应用于列表中的每个项目。我正在尝试将映射转换为尾递归函数,如何才能做到这一点?
推荐答案
您卡在哪里?您可以使用内部loop
过程定义您自己的map
过程。
(define (map f in)
(define (loop out lst)
(if #|exit condition here|#
#|return output|#
(loop (cons #|add to output|# out)
#|sub problem|#)))
(loop null in)) ; run the loop
(map (lambda (x) (* x x)) '(1 2 3 4 5))
'(1 4 9 16 25)
此模式在球拍中非常常见,因此有一个命名的let
语法使我们更容易使用它。
(define (map f in)
(let loop ((out null) (lst in))
(if #|exit condition here|#
#|return output|#
(loop (cons #|add to output|# out)
#|sub problem|#))))
另一个选项是使用延续。
(define (map f in)
(let (loop (return identity) (lst in))
(if #|exit condition|#
(return null)
(loop (lambda (out) (return (cons #|add to output|# out)))
#|sub problem|#))))
这篇关于尾递归映射函数球拍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文