首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归时的方案语法错误

递归时的方案语法错误
EN

Stack Overflow用户
提问于 2015-01-30 00:56:34
回答 1查看 44关注 0票数 0

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

例如,我可能得到类似于(+ (1 + 2) 3)的输入。我想把这个改为(1+ 2) + 3)

以下是我到目前为止所拥有的:

代码语言:javascript
复制
 (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.
)

)

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-30 02:20:13

您必须检查lst参数在开始时是否是一个列表(大小写),否则car和朋友在应用于原子时会失败。试试这个:

代码语言:javascript
复制
(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)))))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28227504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档