0

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!

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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 '())))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.