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

Multiple dispatch

Multiple dispatch

Conferences Box

November 30, 2012
Tweet

More Decks by Conferences Box

Other Decks in Technology

Transcript

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

    determines which implementation to call Single dispatch (JavaScript): a single value is used for dispatch. We’ll look at something new – multiple dispatch. Axel Rauschmayer (2ality.com) Multiple dispatch 2012-11-30 2 / 8
  2. Dispatch: via an object or via a function Polymorphic method:

    dispatch via an object. jane.describe() Person.prototype.describe = function (...) {...}; Employee.prototype.describe = function (...) {...}; Axel Rauschmayer (2ality.com) Multiple dispatch 2012-11-30 3 / 8
  3. Dispatch: via an object or via a function 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 2012-11-30 3 / 8
  4. 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 2012-11-30 4 / 8
  5. Adding methods 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) Axel Rauschmayer (2ality.com) Multiple dispatch 2012-11-30 5 / 8
  6. 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 types: foo(obj1, obj2, obj3) // collaborators, not data In which object should we put the algorithm? Visitor pattern – encapsulate an algorithm: The visitor is a generic function Single dispatch in host is used to trigger visitor methods Axel Rauschmayer (2ality.com) Multiple dispatch 2012-11-30 6 / 8
  7. Languages with multiple dispatch Common Lisp Haskell R Groovy Clojure

    C# 4.0 Axel Rauschmayer (2ality.com) Multiple dispatch 2012-11-30 7 / 8