why does “(def vowel? (set ”aeiou“))” work?

前端 未结 2 1114
慢半拍i
慢半拍i 2021-02-13 05:43

I\'m taking a look at the excellent Clojure tutorial here. In one of the examples it has Clojure code along the following lines:

(def vowel? (set \"aeiou\"))
         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-13 06:02

    Aha! I ended up finding it out myself. It doesn't actually return true or false, rather it returns the first occurrence in the set, or nil if it doesn't occur.

    And because you can use this as a condition (nil being handled as false, and non-nil as true), this works as a nice little hack for checking if a string contains a letter.

    (vowel? (first "abc")) ; => "a"
    (vowel? (first "cba")) ; => nil
    
    (if (vowel? (first "abc"))
           (println "yay")
           (println "oops"))  ; => "yay"
    

提交回复
热议问题