简体   繁体   中英

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

I'm working on an exercise in Clojure (answering input based on if it's a question, written in capital letters and so on) and while it works, I can't pass the required test because my code returns nil along with every correct answer . How can I avoid that?

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

Example from the test:

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))

Thank you in advance!

As John commented your issue is in if , follows some adjustments to fix it:

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

Your response-for method is really returning nil all the time. You likely intended the if condition to be (silence? question) but instead it's being applied to that string literal you intend to be the "then" clause. As this is accidentally currently structured, the "else" is nil .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM