RuntimeException不匹配的分隔符:)clojure.lang.Util.runtimeException(Util.java:221)

时间:2016-11-21 15:33:11

标签: data-structures clojure

我在Clojure中实现了一个Clojure计算器。但是,代码抛出异常:“RuntimeException Unmatched delimiter:”Clojure.lang.Util.runtimeException(Util.java:221)“。我不知道是什么原因造成的。下面是代码。任何帮助表示赞赏

(def prio 
   {'+ 0 ; Define operator priority here
    '- 0
    '* 1
    '/ 1
    'l -1
     'r -1
     'dummy -2})

(def operators #{'+ '- '* '/})

(defn pre-process [s]
"Seperate operands with operators and replace ( with l, ) with r"
(re-seq #"\d+|[\+\-\*\/lr]" 
      (clojure.string/replace s #"\(|\)" {"(" "l" ")" "r"})))

(defn calc-once [stk] 
"Take one operator from operator stack and apply it to 
 top two numbers in operand stack"
 (let [opt (:opt stk)
    num (:num stk)
    tmp-num (pop (pop num))
    tmp-opt (pop opt)
    last-two-num [(peek (pop num)) (peek num)]
    last-opt (peek opt)]
  (assoc stk 
       :num (conj tmp-num (apply (eval last-opt) last-two-num))
       :opt tmp-opt)))

(defn process-stk [stk checker fn-ret]
 (loop [stk stk]
  (if (checker stk)
   (recur (calc-once stk))
   (fn-ret stk))))

(defn calc
"A simple calculator"
 [s]
 (process-stk 
 (reduce
  (fn [stk item]
    (let [item (read-string item)
          add-to-num #(assoc %1 :num (conj (:num %1) %2))
          add-to-opt #(assoc %1 :opt (conj (:opt %1) %2))
          item-prio (get prio item)
          last-prio #(get prio (peek (:opt %)))]
      (cond
        (number? item) ; It's number
        (add-to-num stk item)
        (get operators item) ; It's operator
        (process-stk stk #(<= item-prio (last-prio %))
                     #(add-to-opt % item)) 
        (= 'l item) ; (
        (add-to-opt stk item)
        (= 'r item) ; )
        (process-stk stk #(not= (peek (:opt %)) 'l)
                       #(assoc % :opt (pop (:opt %))))
        :else
        (println "Unexpected syntax: " item))))
    (apply (partial list {:num '() :opt '(dummy)}) ;; Basic structure of stack
           s))
#(> (count (:opt %)) 1)
#(peek (:num %))))

1 个答案:

答案 0 :(得分:1)

  

RuntimeException不匹配的分隔符:)

此错误表示括号不平衡。你在某个地方有一个额外的)