Scheme - 将函数应用于嵌套列表中的元素的Map函数 [英] Scheme - Map function for applying a function to elements in a nested list

查看:158
本文介绍了Scheme - 将函数应用于嵌套列表中的元素的Map函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,(map number?'( 3(2 A)2 Z)应该返回'(#t(#t #f)#t #f)



这是我到目前为止:


 (define(map fun lst)
(if(null?lst)'()
(car lst))
(cons(map fun(car lst)))(map fun(cdl lst)))
(cons(fun ))))

如果嵌套列表位于列表的前端,它可以工作,例如地图编号?'((3 A)2 Z))正确地返回((#t #f)#t #f)

当嵌套列表出现时,会发生问题在原始列表中的另一个元素
例如(map number?'(3 A(2 Z)))错误地返回(#t #f #f)[结果应该是(#t #f(#




$ b

如何更改我的算法以纠正这一点?

解决方这是我的解决方案 - 它非常便宜,它重用内置的地图,使用装饰图案。 (我知道,使用设计模式的计划程序?:-O)

 (define(deep-map fl)
(定义(深x)
(cond((null?x)x)
((pair?x)(map deep x))
(else(fx))))
(map deep l))

这可以通过使用命名的 let

 (define(deep-map fl)
(let deep((xl))
(cond((null?x)x)
((pair?x)(map deep x))
(else(fx))) )

(这两个代码片段不完全相同,但对于这个问题,两者都可以相同如果给出列表作为输入。)



null? pair? code>支票(均为O(1)),以避免使用列表?(这是O(n))。


I'm trying to write a mapping function in scheme that applies a function to each value in a nested list.

For example, (map number? '(3 (2 A) 2 Z) should return '(#t (#t #f) #t #f)

Here's what I have so far:

(define (map fun lst)
    (if (null? lst) '()
        (if (list? (car lst)) 
            (cons (map fun (car lst)) (map fun (cdr lst)))
                 (cons (fun (car lst)) (map fun (cdr lst))))))

It works if the nested list is at the front of the list. For example (map number? '((3 A) 2 Z)) correctly returns ((#t #f) #t #f)

The problem occurs when the nested list occurs after another element in the original list. For example (map number? '(3 A (2 Z))) incorrectly returns (#t #f #f) [The result should be (#t #f (#t #f))]

How can I change my algorithm to correct this?

解决方案

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)).

这篇关于Scheme - 将函数应用于嵌套列表中的元素的Map函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆