简体   繁体   中英

Racket Recursive Square Function

I am trying to write a function in racket that takes in a list of numbers and outputs a list containing the square of those numbers. I am trying to not use the map implementation and instead solve the problem recursively. However, the code I have now is outputting the same list that was the input. The code I have is as follows:

  (define (my-square lst)
         (cond (cons? lst)
               (append  (* (first lst) (first lst))  (my-square (rest lst)))))

I appreciate any help!

The base case is wrong (it should ask for the empty list), and cons should be used for recursively building a list (instead of append ). Also, you have a couple of errors regarding parentheses, and the last condition in a cond should be specified using else . This is the standard template for building an output list:

(define (my-square lst)
  (cond ((empty? lst)
         empty)
        (else
         (cons (* (first lst) (first lst))
               (my-square (rest lst))))))

That's fine for a solution written from scratch, but the idiomatic way to solve this problem in Racket would be to use a higher-order function, such as map - so we don't reinvent the wheel:

(define (my-square lst)
  (map (lambda (x) (* x x)) lst))

Either way, it works as expected:

(my-square '(1 2 3 4 5))
=> '(1 4 9 16 25)

append should be cons , and you should handle the case when lst is empty. Finally, cond conditions should be wrapped in parentheses:

(define (my-square lst)
  (cond ((cons? lst) (cons (* (first lst) (first lst)) (my-square (rest lst))))
        (#t '())))

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