Scheme - Map function for applying a function to elements in a nested list

99封情书 提交于 2019-12-03 21:38:49

Here's my solution---it's seriously cheap in that it reuses the built-in map, using the decorator pattern. (I know, Scheme programs using design patterns? :-O)

(define (deep-map f l)
  (define (deep x)
    (cond ((null? x) x)
          ((pair? x) (map deep x))
          (else (f x))))
  (map deep l))

This can be "simplified" even further by using a named let:

(define (deep-map f l)
  (let deep ((x l))
    (cond ((null? x) x)
          ((pair? x) (map deep x))
          (else (f x)))))

(The two snippets of code are not identical, but for this question, both will work the same if given a list as input.)

The null? and pair? checks (both O(1)) are used in order to avoid using list? (which is O(n)).

Your code is correct, except that it's way too verbose than it could be. Hint: you need to worry about only two cases: whether lst is a pair? or not. That's all. In other words, your code assumes that the input is always a list, but it could be simplified to accept anything, and do the special recursive thing when it's a pair.

As for the problem that you're seeing -- my guess is that you're using Racket, and therefore you're running against an odd case. If this is not the case then you can stop reading here.

The thing is that in Racket the function itself will compile before the binding to map is made, therefore the map calls are not really recursive, but instead they're just calls to the builtin map. Later on, map is (re-)bound to the resulting function, but the recursive calls were already compiled. If you enter the same definition twice, you'll see that it starts working again. The way to solve this is to just not work at the REPL, and instead always write definitions in a file that starts with some #lang <something>.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!