【问题标题】:How to avoid returning 'nil' after string in Clojure?如何避免在 Clojure 中的字符串后返回“nil”?
【发布时间】:2020-12-15 05:29:24
【问题描述】:

我正在 Clojure 中进行一项练习(根据是否为问题回答输入,用大写字母等等),虽然它有效,但我无法通过所需的测试,因为 我的代码返回nil 以及每个正确答案。我怎样才能避免这种情况?

(ns bob
  (:use [clojure.string :only [upper-case blank?]]))

(defn- silence? [question]
  (blank? question))

(defn- yell? [question]
  (and (re-find #".*!$" question) (= question (upper-case question))))

(defn- ask? [question]
  (re-find #".*\?$" question))

(defn response-for [question]
  (if (silence? "Fine, be that way.")
    (case ((juxt yell? ask?) question)
      [true true] "Calm down, I know what I'm doing!"
      [true false] "Woah, chill out!"
      [false true] "Sure."
      "Whatever.")))

测试示例:

FAIL in (responds-to-forceful-talking) (bob_test.clj:25)
expected: (= "Whatever." (bob/response-for "Let's go make out behind the gym!"))
  actual: (not (= "Whatever." nil))

提前谢谢你!

【问题讨论】:

    标签: clojure functional-programming null


    【解决方案1】:

    正如 John 所说,您的问题在于 如果,请进行一些调整以解决它:

    (defn response-for [question]
      (if (silence? question)
        "Fine, be that way."
        (case ((juxt yell? ask?) question)
          [true true] "Calm down, I know what I'm doing!"
          [true false] "Woah, chill out!"
          [false true] "Sure."
          "Whatever.")))
          
    (= "Whatever." (bob/response-for "Let's go make out behind the gym!"))
    

    【讨论】:

      【解决方案2】:

      您的response-for 方法实际上一直在返回nil。您可能打算将if 条件设为(silence? question),但它却被应用于您打算成为“then”子句的字符串文字。由于这是意外的当前结构,因此“else”是nil

      【讨论】:

        猜你喜欢
        • 2019-02-18
        • 2019-02-14
        • 1970-01-01
        • 1970-01-01
        • 2015-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-21
        相关资源
        最近更新 更多