【问题标题】:"Unbound" variables in clojure functionsclojure 函数中的“未绑定”变量
【发布时间】:2017-08-22 05:38:57
【问题描述】:

我正在编写一个函数来将 IRC RFC2813 消息解析为它们的组成部分。这包括两个函数,一个通过正则表达式拆分消息,另一个修改返回以处理某些特殊情况。

(let [test-privmsg ":m@m.net PRIVMSG #mychannel :Hiya, buddy."])

(defn ircMessageToMap [arg]
  "Convert an IRC message to a map based on a regex"
  (println (str "IRCMapifying " arg))
  (zipmap [:raw :prefix :type :destination :message]
          (re-matches #"^(?:[:](\S+) )?(\S+)(?: (?!:)(.+?))?(?: [:](.+))?$"
                      arg
                      )
          )
  )

(defn stringToIRCMessage [arg]
   "Parses a string as an IRC protocol message, returning a map"
     (let [r (doall (ircMesgToMap arg))])
     (println (str "Back from the wizard with " r))
     (cond
       ;Reformat PING messages to work around regex shortcomings
       (= (get r :prefix) "PING") (do
                                    (assoc r :type (get r :prefix))
                                    (assoc r :prefix nil)
                                  )
       ;Other special cases here
       :else r)
  )

我遇到的问题是stringToIRCMessage 函数似乎没有实现 ircMesgToMap 的返回值。如果我评估(stringToIRCMessage test-privmsg)println 语句会给我:

Back from the wizard with Unbound: #'irc1.core/r

..但来自ircMessageToMap 的“IRCMapifying”结果事先出现在控制台上,表明它已被正确评估。

doall 试图强制在函数中间实现结果 - 它没有效果。

我应该如何重写这个stringToIRCMessage 函数以使r 变量可用?

【问题讨论】:

  • 您还必须修复您的(do (assoc ...) (assoc ...)),因为其中第一个无效。请记住,Clojure 值是不可变的,(g (f x))(do (f x) (g x)) 非常不同。

标签: clojure


【解决方案1】:

let 语句中的括号有误。

应该是这样的:

  (let [r (doall (ircMesgToMap arg)) ]
     (println (str "Back from the wizard with " r))
     (cond
       ;Reformat PING messages to work around regex shortcomings
       (= (get r :prefix) "PING") (do
                                    (assoc r :type (get r :prefix))
                                    (assoc r :prefix nil)
                                  )
       ;Other special cases here
       :else r))

【讨论】:

  • 我需要在let 块下拥有整个函数的其余部分?
  • 只关心值r的部分。它是“词法作用域”,就像在 Java、C 等中一样(即它是一个不存在的“局部变量”,即“未绑定”,在块之外)
  • 啊哈。我假设函数中的表单本身将其绑定到函数的范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-31
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
相关资源
最近更新 更多