如何避免在 Clojure 中的字符串后返回 'nil'?

How to avoid returning 'nil' after string in Clojure?

我正在做一个 Clojure 练习(根据是否是问题回答输入,用大写字母等等),虽然它有效,但我无法通过要求的测试,因为 我的代码 returns 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))

提前致谢!

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

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

(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!"))