递归时方案语法错误

Scheme syntax error when recursing

我正在编写一个递归函数,它将表达式从前缀转换为中缀。但是,我需要添加一个检查以确保部分输入尚未在中缀中。

例如,我可能会得到像 (+ (1 + 2) 3) 这样的输入。 我想将其更改为 ((1 + 2) + 3)

这是我目前的情况:

 (define (finalizePrefixToInfix lst)
      ;Convert a given s-expression to infix notation
     (define operand (car lst))
     (define operator1 (cadr lst))
     (define operator2 (caddr lst))    
     (display lst)
     (cond 
         ((and (list? lst) (symbol? operand));Is the s-expression a list?
        ;It was a list. Recusively call the operands of the list and return in infix format
        (display "recursing")
        (list (finalizePrefixToInfix operator1) operand (finalizePrefixToInfix operator2))
    )
    (else (display "not recursing") lst);It was not a list. We can not reformat, so return.
)

)

但是,这会给我语法错误,但我不知道为什么。有帮助吗?

你必须在一开始就检查 lst 参数是否是一个列表(基本情况),否则 car 和朋友在应用于原子时会失败。试试这个:

(define (finalizePrefixToInfix lst)
  (cond ((not (pair? lst)) lst)
        (else
         (define operand   (car lst))
         (define operator1 (cadr lst))
         (define operator2 (caddr lst))    
         (cond 
           ((symbol? operand)
            (list (finalizePrefixToInfix operator1)
                  operand
                  (finalizePrefixToInfix operator2)))
           (else lst)))))