{ "metadata": { "language": "Julia", "name": "", "signature": "sha256:ae9d3a181058f7385d3142d3b3cd1a27b27bf4c6bb72dcee608b228cbe0ff792" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "(Dynamic) Multiple Dispatch in Julia" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Multiple dispatch](http://en.wikipedia.org/wiki/Multiple_dispatch) can be thought of as a generalization of **object-oriented** (OO) programming.\n", "\n", "In a typical OO language like Python, an object type (class) *owns* certain *methods* (functions), and are typically called via\n", "```\n", "object.method(arg1, arg2)\n", "```\n", "Depending on the type of `object`, the runtime system will *dispatch* to different `method` definitions.\n", "\n", "In Julia, the same call would be \"spelled\" differently:\n", "```\n", "method(object, arg1, arg2)\n", "```\n", "Spelled this way, you should notice something odd about OO programming: why is the *first* argument so special?\n", "\n", "Traditional OO programming corresponds to **single dispatch**: the runtime chooses `method` based on the type of the *first* argument only. Julia implements **multiple dispatch**: the runtime chooses `method` based on the types of *all* the arguments." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Example: Binary mathematical operators" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A classic example of the need for multiple dispatch is the case of binary math operators. If you compute `x * y`, the definition of the `*` function depends upon *both* the arguments, not just on `x`.\n", "\n", "Julia defines *many versions* of the `*` function:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "methods(*)" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "130 methods for generic function *: