我正在编写一个递归函数,它将将表达式从前缀转换为infix。但是,我需要添加一个检查,以确保部分输入没有在infix中。
例如,我可能得到类似于(+ (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.
)
)然而,这给了我语法错误,但我不知道为什么。有什么帮助吗?
发布于 2015-01-30 02:20:13
您必须检查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)))))https://stackoverflow.com/questions/28227504
复制相似问题