简单方案,对列表中的所有元素进行平方

时间:2012-10-21 23:05:00

标签: scheme

好吧,我是Scheme的新手,我以为我明白了,但对这个问题感到困惑。我想要对列表中的所有元素进行平方。所以,(mapsq'(1 2 3))返回(列表1 4 9)。

我的代码:

(define mapsq
  (lambda (ls)
    (cond ((null? ls) 0)
          (else (cons (car ls) (car ls))
                (mapsq (cdr ls)))))))

3 个答案:

答案 0 :(得分:3)

在实际(非学术)环境中,使用map程序可以轻松解决此问题:

(define mapsq
  (lambda (ls)
    (map (lambda (x) (* x x))
         ls)))

当然,如果这是家庭作业,你需要从头开始实施解决方案,我不应该用勺子喂答案。更好地找出解决方案,填写空白:

(define mapsq
  (lambda (ls)
    (cond ((null? ls)               ; If the list is empty
           <???>)                   ; ... then return the empty list.
          (else                     ; Otherwise
           (cons (* <???> <???>)    ; ... square the first element in the list
                 (mapsq <???>)))))) ; ... and advance the recursion.

您的解决方案中存在两个问题:首先,基本情况不应返回0 - 如果我们正在构建一个列表作为答案,那么您必须返回空列表。其次,在递归步骤中,您实际上并没有对列表中的当前元素进行平方 - 为此,只需将其与*运算符相乘即可。

答案 1 :(得分:1)

你可以这样写:

(define (mapsq xs)
  (define (square x) (* x x))
  (map square xs))

或者这个:

(define (mapsq xs)
  (map (lambda (x) (* x x)) xs))

或者也许是这样:

(define (mapsq xs)
  (let loop ((xs xs) (sqs '()))
    (if (null? xs)
        (reverse sqs)
        (loop (cdr xs) (cons (* (car xs) (car xs)) sqs)))))

或者甚至喜欢这样:

(define (mapsq xs)
  (if (null? xs)
      '()
      (cons (* (car xs) (car xs)) (mapsq (cdr xs)))))

我的偏好是第一个选择。第二个选项较短,但辅助功能使第一个选项更容易阅读。我可能不会使用第三或第四选项。

顺便说一句,laser_wizard的解决方案也不起作用。

我注意到你是新来的。如果您喜欢答案,请单击答案旁边的向上箭头,以便给出答案的人获得积分;这个标记也让读者群体知道答案中有一些有价值的东西。一旦你有一个自信是正确的答案,点击答案旁边的复选标记;这也为给出答案的人提供了积分,更重要的是让其他读者知道你认为这个答案最正确地解决了你的问题。

答案 2 :(得分:1)

(define (mapsq xs)
  (map * xs xs))

> (mapsq '(1 2 3 4 5))
'(1 4 9 16 25)