Julia-style multiple dispatch

Multiple dispatch is the ability to define multiple implementations of a function, chosen at runtime based on the arguments to each call. The dispatch package brings this to Racket, allowing lexically separate but associated definitions:

(define/dispatch (add [l1 list?]
                      [l2 list?])
  (append l1 l2))

(define/dispatch (add [n1 number?]
                      [n2 number?])
  (+ n1 n2))

> (add 1 2)
3
> (add '(one two) '(three four))
'(one two three four)

Source is here, any contributions are welcome.

11 Likes

Can you compare the package with https://docs.racket-lang.org/multimethod/? How are they different?

2 Likes
  • multimethods can only consider structs, dispatch works with any predicate
  • multimethod requires an explicit definition of a procedure as generic, dispatch handles it automatically
  • each instance of a multimethod must have the same arity, this is not required for dispatch

Edit: I just saw the multimethod blog post. dispatch is fully unsafe as defined there. I don't mind this as a tradeoff but it's something to be aware of.

4 Likes