【问题标题】:Scheme, how to square just negative numbers in a list leaving the rest of the list intact方案,如何将列表中的负数平方,使列表的其余部分保持不变
【发布时间】:2012-10-31 00:40:28
【问题描述】:

我一直在进行累积调用,如下所示:

(define (accumulate op initial sequence)
  (if (null? sequence)
      initial
      (op (car sequence)
          (accumulate op initial (cdr sequence)))))

但是,当我尝试通过过滤器选择某些东西来解决问题时,答案不起作用。我到目前为止是这样的:

(define (f2b items)
   (accumulate (lambda (x y)
     (cons (append 
        (map square (filter negative? (filter number? x))) x) y)) () items)
  )

我给出的输入是:

(f2a '(("sdas" 89) (-53 "sad")))

我得到的输出是:

 ((sdas 89) (2809 -53 sad))

我似乎无法让负数消失。

【问题讨论】:

  • 你的输入是什么?看起来您有一个包含两个列表的嵌套列表,但您的代码无法处理。
  • @GregHewgill 我输入了我提供的信息。

标签: list scheme mit-scheme accumulate


【解决方案1】:

使用过滤器和地图会容易得多。过滤器是预定义的,但看起来像这样。

   (define (filter1 predicate sequence)
          (cond 
               ((null? sequence) null)
                ((predicate (car sequence))
                 (cons (car sequence)
                       (filter predicate (cdr sequence))))
                (else (filter predicate (cdr sequence)))))

map 也是预定义的,它只是在列表上运行一个函数。

这应该很容易编写,但如果您需要帮助,您应该为过滤器中的谓词编写一个 lamdba。

【讨论】:

    【解决方案2】:

    实际上,您描述的功能通常不是累加器的工作。相反,对列表中的负数求平方似乎是地图之类的完美工作。

    首先,让我们开始吧:

    (define (make-positive x)
        (if (and (number? x) (negative? x))
            (square x)
            x))
    

    现在假设我们要对名为lst 的列表进行操作。如果它只是一个平面列表,比如'(1 "2" -5 -4 6),那么我们就可以

    (map make-positive lst)
    

    由于我们需要对嵌套两层的列表进行操作,我们可以这样做:

    (map (lambda (x)
            (map make-positive x))
         lst)
    

    如果我们想对嵌套任意深度的列表进行操作,我们可以这样做:

    (define (nested-map fn elm)
       (if (list? elm)
           (map (lambda (x) (nested-map fn x)) elm)
           (fn elm)))
    
    (nested-map make-positive lst)
    

    PS - 我们可以这样定义map

    (define (map fn lst)
       (if (empty? lst)
           '()
           (cons (fn (car lst))
                 (map fn (cdr lst)))))
    

    【讨论】:

    • 谢谢!我不知道为什么我没有想到使用地图,但是,这很有意义!
    猜你喜欢
    • 1970-01-01
    • 2021-05-24
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多