Recursion 递归时出现方案语法错误

Recursion 递归时出现方案语法错误,recursion,scheme,Recursion,Scheme,我正在编写一个递归函数,将表达式从前缀转换为中缀。但是,我需要添加一个检查,以确保输入的一部分不在中缀中 例如,我可能会得到类似(+(1+2)3)的输入。 我想把它改成((1+2)+3) 以下是我到目前为止的情况: (define (finalizePrefixToInfix lst) ;Convert a given s-expression to infix notation (define operand (car lst)) (define operat

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

例如,我可能会得到类似(+(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
和friends在应用于atom时将失败。试试这个:

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

请注意,在Racket之外(基本上是cons单元可变的任何方案实现),
list?
是O(n)。所以通常我会尽量少用它,除非我知道自己在忙。是的,最好使用
pair?
:)只有两件事。在第二个
cond
中,我们已经知道
lst
是成对的。我们还应该检查长度是否安全,即使是O(n)。@Rptx感谢您的反馈!我采纳了你的第一个建议。但是我会假设表达式是格式良好的,否则代码在所有的错误检查中看起来会很难看:PWell。OP已经给了它一个半中缀表达式,一个非3元素列表似乎不是不可能的。但如你所愿。不客气。如果您添加了从解释器得到的错误,这将非常有用。“语法错误”说的不多。