# Julia-style multiple dispatch

**URL:** <https://racket.discourse.group/t/julia-style-multiple-dispatch/1936>\
**Category:** Show & Tell\
**Tags:** package\
**Created:** [May 11, 2023, 3:58am UTC](https://racket.discourse.group/t/julia-style-multiple-dispatch/1936 "2023-05-11T03:58:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![a11ce](https://yyz2.discourse-cdn.com/free1/user_avatar/racket.discourse.group/a11ce/32/431_2.png) [@a11ce](https://racket.discourse.group/u/a11ce)\
**Post date:** [May 11, 2023, 3:58am UTC](https://racket.discourse.group/t/julia-style-multiple-dispatch/1936/1 "2023-05-11T03:58:58Z")

</div>

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:

```scheme
(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](https://github.com/a11ce/dispatch/), any contributions are welcome.

---

<div class="post-metadata">

**Author:** ![sorawee](https://avatars.discourse-cdn.com/v4/letter/s/ea5d25/32.png) [@sorawee](https://racket.discourse.group/u/sorawee)\
**Post date:** [May 11, 2023, 4:14am UTC](https://racket.discourse.group/t/julia-style-multiple-dispatch/1936/2 "2023-05-11T04:14:29Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![a11ce](https://yyz2.discourse-cdn.com/free1/user_avatar/racket.discourse.group/a11ce/32/431_2.png) [@a11ce](https://racket.discourse.group/u/a11ce)\
**Post date:** [May 11, 2023, 4:27am UTC](https://racket.discourse.group/t/julia-style-multiple-dispatch/1936/3 "2023-05-11T04:27:56Z")

</div>

- `multimethod`s 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](https://lexi-lambda.github.io/blog/2016/02/18/simple-safe-multimethods-in-racket/). `dispatch` is fully unsafe as defined there. I don't mind this as a tradeoff but it's something to be aware of.
