我正试图在clojure中实现餐饮哲学家的例子。 由于某些原因,我的程序总是因为
的例外而死“java.lang.UnsupportedOperationException:nth不支持此 type:Boolean“
我无法理解这个错误消息,因为我已经尝试从与第n个完美配合的列表中获取布尔值
我猜错误发生在函数 philosopher-thread
中的 if语句控制台打印:
代码:
(ns dining-philosphers.core
(:gen-class))
(defn think [n]
(println (str n " is thinking"))
(Thread/sleep (rand 1000))
(println (str n " after sleep"))
)
(defn eat [n]
(println (str n " is eating"))
(Thread/sleep (rand 1000))
)
(def isEating (atom '(false false false false false)))
(defn philosopher-thread [n]
(Thread. #(
(while true (do
(think n)
(println (str n " after think"))
(if (or (nth @isEating (mod (- n 1) 5)) (nth @isEating (mod (+ n 1) 5)))
(println "is waiting for neighbour")
(
do
(println (str n " swap"))
(swap! isEating (fn [l] assoc l n true))
(eat n)
(swap! isEating (fn [l] assoc l n true))
)
)
)
)
)
)
)
(defn -main [& args]
(let [threads (map philosopher-thread (range 5))]
(doseq [thread threads] (.start thread))
(doseq [thread threads] (.join thread))))
答案 0 :(得分:5)
你在这里错过了一些问题:
(swap! isEating (fn [l] assoc l n true))
应该是
(swap! isEating (fn [l] (assoc l n true)))
第一个将按顺序评估assoc
,l
,n
和true
,并返回最后一个表达式的值(true
)
仍然存在一个问题,即您无法assoc
进入列表。我建议改用矢量:
(def isEating (atom [false false false false false]))