简体   繁体   中英

Multiply two lists in Racket

I am using Racket to multiply to list with the same length. So far I have tried:

(define (multiply-list a b)
  (if ([(empty? a) (empty)])
      else (cons(*car(a)car(b)))
      cdr(a) cdr(b)))                  

I am having trouble understanding the syntax of Racket. I want to update the list to it's cdr . but I cannot get it right a and b are the lists.

I believe you were aiming for something like this:

(define (multiply-list a b)
  (if (empty? a)
      empty
      (cons (* (car a) (car b))
            (multiply-list (cdr a) (cdr b)))))

Explanation:

  • In Scheme, we have to be very, very careful where we put a pair of () . In your code, some parentheses are unnecessary and others are misplaced. A good IDE will help you put them in the right place
  • For instance, the pair of [] surrounding the condition are wrong, and so is this: (empty) because empty is not a function, we surround something with () when we want to call it like a function
  • And we don't call a function like this: car(a) . The correct way is: (car a)
  • When we use if , the alternative part of the expression must not be preceded by else , maybe you're confusing an if expression with a cond expression.
  • And last but not least: don't forget to call the recursion!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM