Ploymorphism
Usually you define a function with one set of arguments, either none []
, one [one]
or many [any number of args]
, using the basic syntax
(defn name
"I am the doc string to describe the function"
[args]
(str "define your behaviour here"))
Instead of writing multiple functions with the same name that each take different numbers of arguments, you can use the following polymorphic syntax in Clojure
(defn name
"I am the doc string to describe the function"
([]
(str "behaviour with no args"))
([one]
(str "behaviour with one arg"))
([one two & args]
(str "behaviour with multiple args")))
Note Write a simple function called
i-am-polly
that returns a default message when given no arguments and a custom message when given a custom string as an argument
(defn i-am-polly
([] (i-am-polly "My name is polly"))
([message] (str message)))
(i-am-polly)
(i-am-polly "I call different behaviour depeding on arguments sent")
当前内容版权归 practicalli 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 practicalli .