【问题标题】:Nested Let in Anglican ClojureAnglican Clojure 中的嵌套 Let
【发布时间】:2019-02-27 08:54:04
【问题描述】:

我是 Clojure 中的概率编程语言 Anglican 的新手。我正在尝试在 Clojure 中使用嵌套的 let 构造。

以下defquery运行没有任何问题。

(defquery panda3 [p1]
  (let [p2 (sample 
              (categorical
                {:speA (/ 1 2),
                 :speB (/ 1 2)}))]
    (if (= p2 :speA)
      ( let [p3 (sample 
              (categorical
                {:twins (/ 1 10),
                 :notwins (/ 9 10)}))] 

      )
      ( let [p3 (sample 
              (categorical
                {:twins (/ 2 10),
                 :notwins (/ 8 10)}))]

      ))

    p2))

但是,如果我尝试返回 p3 的值,而不是最后返回 p2 的值,它会返回错误。

(defquery panda3 [p1]
  (let [p2 (sample 
              (categorical
                {:speA (/ 1 2),
                 :speB (/ 1 2)}))]
    (if (= p2 :speA)
      ( let [p3 (sample 
              (categorical
                {:twins (/ 1 10),
                 :notwins (/ 9 10)}))] 

      )
      ( let [p3 (sample 
              (categorical
                {:twins (/ 2 10),
                 :notwins (/ 8 10)}))]

      ))

    p3))

这个想法是根据 p2 的结果分配 p3。但是,我无法这样做。我究竟做错了什么?

提前致谢,

【问题讨论】:

  • let 定义在let 的主体中可用的局部变量。在您尝试返回p3 的位置,p3 未定义。

标签: clojure


【解决方案1】:

正如评论所说,您需要从定义它的let 范围内返回p3

(defquery panda3 [p1]
  (let [p2 (sample 
              (categorical
                {:speA (/ 1 2),
                 :speB (/ 1 2)}))]
    (if (= p2 :speA)
      (let [p3 (sample 
                 (categorical
                   {:twins (/ 1 10),
                    :notwins (/ 9 10)}))] 
        p3)
      (let [p3 (sample 
                 (categorical
                   {:twins (/ 2 10),
                    :notwins (/ 8 10)}))]
        p3 ))))

更新

正如 amalloy 指出的,第二部分可能是:

  ; return the result of `(sample (categorical ...))` called
  ; with one of the 2 maps
  (if (= p2 :speA)
    (sample 
      (categorical
        {:twins (/ 1 10),
         :notwins (/ 9 10)} ))
    (sample 
      (categorical
        {:twins (/ 2 10),
         :notwins (/ 8 10)} )))

甚至

  ; return the result of `(sample (categorical ...))` called
  ; with one of the 2 maps
  (sample 
    (categorical
      (if (= p2 :speA)
        {:twins (/ 1 10),
         :notwins (/ 9 10)}
        {:twins (/ 2 10),
         :notwins (/ 8 10)} )))

【讨论】:

  • 更好:(let [p3 (sample (categorical (if ...)))] ...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2015-10-18
  • 2015-11-17
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多