Scheme 方案:遍历整个列表
我有一个程序,它接受像“((1加2)(2乘以2))这样的输入。但是,当我运行该示例输入时,它只输出'(3)。我如何更改此代码以解析我给出的整个列表,而不仅仅是列表中的第一个实例Scheme 方案:遍历整个列表,scheme,racket,Scheme,Racket,我有一个程序,它接受像“((1加2)(2乘以2))这样的输入。但是,当我运行该示例输入时,它只输出'(3)。我如何更改此代码以解析我给出的整个列表,而不仅仅是列表中的第一个实例 (define math (lambda (lst) (cond [(null? lst) lst] [(equal? (second (car lst)) 'plus) (cons (+ (first (car lst)) (third (car lst))) '())]
(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))) '())])
))
您需要推进递归,因此该过程将继续处理列表中的其余表达式。试试这个:
(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
它按预期工作:
(math '((1 plus 2) (2 times 2)))
=> '(3 4)