我需要根据字符串的第一个字符做出决策,我定义了以下这个方法:
(defn check-first [string]
(case (get string 0)
"+" 1
"-" 2
3
))
目前,即使字符串以那些字符开头,它始终返回3。我做错了什么?此外,有没有更优雅的实现方式?
(get "foo" 0)
;; => \f
(get "foo" 0)
返回一个char
而不是一个string
,所以如果你想使用你的check-first
,你需要用字符替换字符串。
(defn check-first [s]
(case (first s) \+ 1, \- 2, 3))
s
作为参数名称。(str (first "foo"))
或(subs "foo" 0 1)
=> "f"
或者,可以编写一个case-indexed
宏。(defmacro case-indexed [expr & clauses]
(list* 'case expr (interleave clauses (iterate inc 1))))
;; (case-indexed "foo" "bar" "baz" "foo") => 3
;; (case-indexed (+ 5 1) 3 4 5 6 7) => 4
(defn check-first [s]
(case-indexed (first s)
\+, \-, \*, \/))
您可以保留原有内容,并在case条件中使用Java的substring方法:
(defn check-first [s]
(case (.substring s 0 1)
"+" 1
"-" 2
3))
编辑:刚刚注意到MayDaniel已经提到了subs
,它的用法与.substring
相同。抱歉,这里还很早...
您是不是想使用cond?
http://clojure-notes.rubylearning.org/
(def x 10)
(cond
(< x 0) (println "Negative!")
(= x 0) (println "Zero!"))
; => nil
(cond
(< x 0) (println "Negative!")
(= x 0) (println "Zero!")
:default (println "Positive!"))
; => Positive!