【问题标题】:Clojure: nth not supported on this type: Boolean"Clojure:此类型不支持第 nth:布尔“
【发布时间】:2016-11-11 07:44:24
【问题描述】:

我正在尝试在 clojure 中实现用餐哲学家的示例。 由于某些原因,我的程序总是死掉一个例外,说

"java.lang.UnsupportedOperationException: nth 不支持 类型:布尔值"

我无法理解此错误消息,因为我已经尝试从与 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))))

【问题讨论】:

    标签: clojure clojure-java-interop


    【解决方案1】:

    您在这里缺少一些括号:

    (swap! isEating (fn [l] assoc l n true)) 
    

    应该是

    (swap! isEating (fn [l] (assoc l n true))) 
    

    第一个将依次计算assoclntrue,并返回最后一个表达式的值(true

    还有一个问题,就是你不能把assoc放到一个列表里。我建议改用向量:

    (def isEating (atom [false false false false false]))
    

    【讨论】:

      猜你喜欢
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多