這是另一種做我認爲你想做的事的方法。不要將變量的類別定義爲其值,請使用Clojure映射。例如使用基本{}
地圖語法:
(def what-is-map {"dog" "animal"
"cat" "animal"
"Fiat" "auto"
"flu" "illness"})
(defn what-is [thing]
(str thing " is an " (what-is-map thing)))
最後一個表達式工作,因爲地圖可以像在許多情況下函數中使用。
(what-is "dog") ;=> "dog is an animal"
(what-is "flu") ;=> "flu is an illness"
您還可以爲地圖中未包含的東西提供默認值。這裏有一種方法:
(defn what-is [thing]
(let [what-it-is (what-is-map thing)]
(if what-it-is
(str thing " is a " what-it-is)
(str "I don't know what a " thing " is"))))
的if
作品,因爲當鑰匙未在地圖中找不到,則返回nil
。 (nil
是假的價值觀之一。另一種是false
。)
(what-is "fish") ;=> I don't know what a fish is"
還有其他的,也許是更好的方法來寫這些功能,但我想保持基本的東西。
謝謝@Sam Estep。這就是我要找的。 – omar
爲什麼一個引用的運算符像'('name 5); ==> nil'在Clojure中工作? – Sylwester
@Sylwester是;請參閱我對[此問題]的回答(http://stackoverflow.com/q/35541931/5044950)。 'Symbol'類提供['invoke']的實現(https://github.com/clojure/clojure/blob/clojure-1.8.0/src/jvm/clojure/lang/Symbol.java#L125-L127 )相當於['get'](https://clojuredocs.org/clojure.core/get)。 –