Search code examples
clojure

Canonical approach to return based on type of the argument in Clojure


If the argument is a symbol return it. If the argument is a list call another method.

New to Clojure and cannot find the canonical way to do it. In Python, one could do:

def return_on_arg_type(arg):
  if type(arg) is str:
    return arg
  if type(arg) is list:
    return another_method(arg)

May be I could use multi-methods but how to match on type of the argument and also is matching on type acceptable in Clojure?


Solution

  • There's essentially 3 dispatch methods in Clojure:

    1. Use cond combined with predicates (that's methods that return true or false and often have a name ending in ?) as Alan has described.
    2. Use Protocols which dispatch on the type of the first argument. The reference documentation for this would be at https://clojure.org/reference/protocols
    3. Multimethods. You can think of Multimethods as a programmable dispatch method. They can do much more than just look at the type of their arguments, they could also look into arguments, count elements on a vector argument and much more. Canonical documentation at https://clojure.org/reference/multimethods

    Take a look at Clojure multimethods vs. protocols for a short discussion on Multimethods vs Protocols.