Clojure Dynamic Binding

后端 未结 2 1388
无人及你
无人及你 2020-12-16 21:58

I realize the following is a bad idea for many reasons. I also realize that given I have a stackoverflow rep of 23, it\'s nature to assume that I\'m a newb learning to progr

2条回答
  •  天命终不由人
    2020-12-16 22:19

    If you really want to make animal types talk idiomatically, use Clojure Protocols:

    (defprotocol ISpeak
      (speak [animal] "make the type say it's thing"))
    
    (deftype Dog []
      ISpeak
      (speak [this] "Woof!"))
    
    (deftype Cat []
      ISpeak
      (speak [_] "Meow!!")) ;;you can "drop" the item if not used using _
    
    (def a-dog (Dog.))
    (speak a-dog)
    ;;=>"Woof!"
    
    (def a-cat (Cat.))
    (speak a-cat)
    ;;=>"Meow!!"
    

    Please note you can extend any type (class) with the speak method.

    (extend java.util.Random
      ISpeak
      {:speak (fn [_] "I'm throwing dices at you!")})
    
    (speak (java.util.Random.))
    ;;=>"I'm throwing dices at you!"
    

    The syntax is a bit different for Java classes, please see the Protocols documentation for more information.

提交回复
热议问题