DrRacket - why is this number negative?

早过忘川 提交于 2019-12-13 11:03:16

问题


So I can not figure out why my numbers are negative in this function. Also, the input for calculate is supposed to be a list of the same 3 if someone could give me a hand with that as well, it would be much appreciated. Thank you.

calculate takes the first number in the list, then multiplies it by the second number in the list and subtracts the third number from the input list.

((calculate '(8 3 7)) '(4 8 2 9)) should return '(29 41 23 44)

(define (calculateHelper n m o L)
  (if (null? L) empty
      (cons ((calculate n m o) (car L)) 
            (calculateHelper n m o (cdr L)))))

;((calculate 8 3 7) '(4 8 2 9))
(define (calculate n m o)
   (lambda (L)
     (if (list? L) (calculate n m o L)
         (- o (* m (+ n L))))))

回答1:


Among other things, your subtraction was inverted. This should help:

(define (calculate n m o)
  (lambda (L)
    (map (lambda (e)
           (- (* m (+ n e)) o))
         L)))

then

> ((calculate 8 3 7) '(4 8 2 9))
'(29 41 23 44)

EDIT: to call calculate with a list, you could for example use apply to destructure:

(define (calculate nums)
  (apply (lambda (n m o) 
           (lambda (L)
             (map (lambda (e)
                    (- (* m (+ n e)) o))
                  L)))
         nums))

then

> ((calculate '(8 3 7)) '(4 8 2 9))
'(29 41 23 44)


来源:https://stackoverflow.com/questions/49740700/drracket-why-is-this-number-negative

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