0

I have a program that takes in an input like '((1 plus 2) (2 times 2)). However, when I run that example input, it only prints out '(3). How can I change this code to parse through the whole list that I give it and not just the first instance in the list?

(define math (lambda (lst) (cond [(null? lst) lst] [(equal? (second (car lst)) 'plus) (cons (+ (first (car lst)) (third (car lst))) '())] [(equal? (second (car lst)) 'times) (cons (* (first (car lst)) (third (car lst))) '())]) )) 

1 Answer 1

1

You need to advance the recursion, so the procedure will continue with the rest of the expressions in the list. Try this:

(define math (lambda (lst) (cond [(null? lst) lst] [(equal? (second (car lst)) 'plus) (cons (+ (first (car lst)) (third (car lst))) (math (cdr lst)))] ; advance the recursion [(equal? (second (car lst)) 'times) (cons (* (first (car lst)) (third (car lst))) (math (cdr lst)))]))) ; advance the recursion 

It works as expected:

(math '((1 plus 2) (2 times 2))) => '(3 4) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.