简体   繁体   English

尾递归 Map function RACKET

[英]Tail recursive Map function RACKET

The map function in Racket takes a function and a list and applies the function to each of the items of the list recursively. Racket 中的 map function 接受一个 function 和一个列表,并将 function 递归地应用于列表中的每一项。 I'm trying to convert the map into a tail-recursive function, how can this be done?我正在尝试将 map 转换为尾递归 function,该怎么做?

Where are you getting stuck?你卡在哪儿了? You can define your own map procedure with an inner loop procedure.您可以使用内部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)

This pattern is so common in racket that there is a named let syntax that makes it easier for us to use.这种模式在 racket 中非常常见,以至于有一个命名为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|#))))

Another option is to use continuations.另一种选择是使用延续。

(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|#))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM