Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Multiple dispatch

Multiple dispatch

Avatar for Axel Rauschmayer

Axel Rauschmayer

November 11, 2013
Tweet

More Decks by Axel Rauschmayer

Other Decks in Programming

Transcript

  1. What is method dispatch? Polymorphic method: multiple implementations ⇒ dispatch

    determines which implementation to call Single dispatch (JavaScript): single value used for dispatch. Multiple dispatch: uses multiple values. Axel Rauschmayer (2ality.com) Multiple dispatch 2013-11-11 2 / 9
  2. Polymorphic method: dispatch via an object. jane.describe() Person.prototype.describe = function

    (...) {...}; Employee.prototype.describe = function (...) {...}; Generic function: dispatch via a function. describe(jane) function describe(self) { if (self instanceof Person) { ... } else if (self instanceof Employee) { ... } } Axel Rauschmayer (2ality.com) Multiple dispatch 2013-11-11 3 / 9
  3. Generic function: more than one parameter function plus(op1, op2) {

    if (typeof op1 === 'number' && typeof op2 === 'string') { ... } else if (typeof op1 === 'string' && typeof op2 === 'number') { ... } } Axel Rauschmayer (2ality.com) Multiple dispatch 2013-11-11 4 / 9
  4. Adding cases to a generic function var plus = new

    GenericFunction(); plus.addMethod([num, str], function (op1, op2) { ... }); plus.addMethod([str, num], function (op1, op2) { ... }); plus(3, 'abc') plus('abc', 3) (In languages with multiple dispatch, the cases are called methods.) Axel Rauschmayer (2ality.com) Multiple dispatch 2013-11-11 5 / 9
  5. Benefits of multiple dispatch What happens? Symmetry: all parameters as

    important as this (implicit parameter in single dispatch) Functions become object-oriented, aware of type hierarchy. Benefits: Useful whenever a polymorphic algorithm spans several objects: foo(obj1, obj2, obj3) // collaborators, not data In which object should we put the algorithm? Extend existing “classes” in an easy, modular fashion. Axel Rauschmayer (2ality.com) Multiple dispatch 2013-11-11 6 / 9
  6. Multiple dispatch is better than visitor pattern Visitor pattern (single

    dispatch): Algorithm encapsulated as object: visitor Data: client client.accept(visitor) The visitor is (almost) a generic function! Multiple dispatch: visitor(client) Axel Rauschmayer (2ality.com) Multiple dispatch 2013-11-11 7 / 9
  7. Languages with multiple dispatch Common Lisp Haskell R Groovy Clojure

    C# 4.0 Axel Rauschmayer (2ality.com) Multiple dispatch 2013-11-11 8 / 9