Clojure:此类型不支持第 n 个:布尔值”
Clojure: nth not supported on this type: Boolean"
我正在尝试在 Clojure 中实现哲学家就餐示例。
由于某些原因,我的程序总是死于异常
"java.lang.UnsupportedOperationException: nth not supported on this
type: Boolean"
我无法理解此错误消息,因为我已经尝试从与 nth 完美配合的列表中获取布尔值
我猜错误发生在函数 philosopher-thread 中的 if 语句
控制台打印:
- 3正在思考
- 1 正在思考
- 4正在思考
- 0正在思考
- 2正在思考
- 0 睡后
- 0 思考后
- 0 交换
- 0 正在吃东西
- 3 睡后
- 三思后
代码:
(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))))
您在这里遗漏了一些括号:
(swap! isEating (fn [l] assoc l n true))
应该是
(swap! isEating (fn [l] (assoc l n true)))
第一个将按顺序计算assoc
、l
、n
和true
,return最后一个表达式的值(true
)
还有一个问题,就是无法assoc
上榜。我建议改用矢量:
(def isEating (atom [false false false false false]))
我正在尝试在 Clojure 中实现哲学家就餐示例。 由于某些原因,我的程序总是死于异常
"java.lang.UnsupportedOperationException: nth not supported on this type: Boolean"
我无法理解此错误消息,因为我已经尝试从与 nth 完美配合的列表中获取布尔值
我猜错误发生在函数 philosopher-thread 中的 if 语句
控制台打印:
- 3正在思考
- 1 正在思考
- 4正在思考
- 0正在思考
- 2正在思考
- 0 睡后
- 0 思考后
- 0 交换
- 0 正在吃东西
- 3 睡后
- 三思后
代码:
(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))))
您在这里遗漏了一些括号:
(swap! isEating (fn [l] assoc l n true))
应该是
(swap! isEating (fn [l] (assoc l n true)))
第一个将按顺序计算assoc
、l
、n
和true
,return最后一个表达式的值(true
)
还有一个问题,就是无法assoc
上榜。我建议改用矢量:
(def isEating (atom [false false false false false]))