gpt4 book ai didi

clojure - 调车场算法

转载 作者:行者123 更新时间:2023-12-04 06:28:28 25 4
gpt4 key购买 nike

我正在 Clojure 中实现一个中缀计算器,首先是我实现了 Dijkstra 的 Shunting-yard 算法。我以为我已经很好地解决了它,但是我开玩笑,它似乎根本无法很好地处理运算符(operator)。调用 (shunting-yard "3 + 5") => (\3) .就这样。有人能告诉我我在这里处理操作符字符有什么问题吗?

(import '(java.lang.Character))

(defn operator? [sym]
"Determines if a given token is a mathematical operator."
(some #{sym} '(\+ \- \* \/ \% \^ \!)))

(defn associativity-of [operator]
"Determines the associativity of a given mathematical operator."
(if (some #{operator} '(\+ \- \* \/ \%))
'left
'right))

(defn precedence-of [operator]
"Determines the precedence of a given mathematical operator."
(case operator
(\+ \-) 2
(\* \/ \%) 3
(\^ \!) 4
0))

(defn operator-actions [stmt stack]
"Actions taken when the next token in the stmt is an operator."
(let [token-prec (precedence-of (first stmt))
token-assoc (associativity-of (first stmt))
stack-oper (first stack)
stack-prec (precedence-of stack-oper)]
(cond (or (and (= token-assoc 'left)
(<= token-prec stack-prec))
(and (= token-assoc 'right)
(< token-prec stack-prec)))
(cons stack-oper (shunt stmt (rest stack)))
:else (shunt (rest stmt) (cons (first stmt) stack)))))

(defn stack-operations [stack]
"Actions to take if (nil? stmt)"
(comment "If a left paren is found on the stack, it means
that there was no right paren to match it, and
therefore the statement had unbalanced parentheses.")
(cond (and (not (nil? stack))
(= (first stack) \()) (print "Unbalanced parentheses.\n")
(nil? stack) ()
:else (cons (first stack) (stack-operations (rest stack)))))

(defn shunt [stmt stack]
(cond (empty? stmt) (stack-operations stack)
(Character/isDigit (first stmt)) (cons (first stmt)
(shunt (rest stmt) stack))
(operator? (first stmt)) (operator-actions stmt stack)
(= (first stmt) \() (recur (rest stmt) (cons (first stmt) stack))
(= (first stmt) \)) (if (= (first stack) \()
(recur (rest stmt) (rest stack))
(cons (first stack) (shunt stmt (rest stack))))))

(defn shunting-yard [stmt]
(shunt stmt ()))

最佳答案

我实际上不知道 Shunting-Yard 算法(刚刚在维基百科中节省了 2 分钟),但我看到的一个问题是 shunt不处理空格。所以它读取您的 \3 ,递归并退出,因为下一个字符是 \space .如 stmt没有空格,即 "3+5" ,你会得到一个 StackOverflowError ,但我想这是进步。

关于clojure - 调车场算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5737903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com