Created
November 19, 2014 01:31
-
-
Save alco/34d40cc2921c981b74ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defprotocol Addition do | |
@fallback_to_any true | |
def a + b | |
end | |
defimpl Addition, for: Any do | |
def a + b do | |
Kernel.+(a, b) | |
end | |
end | |
defmodule Complex do | |
defstruct re: 0, im: 0 | |
end | |
defimpl Addition, for: Complex do | |
def %Complex{re: re1, im: im1} + %Complex{re: re2, im: im2} do | |
%Complex{re: Kernel.+(re1, re2), im: Kernel.+(im1, im2)} | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
iex(1)> Addition.+(3, 4) | |
7 | |
iex(2)> c1 = %Complex{re: 1, im: 2} | |
%Complex{im: 2, re: 1} | |
iex(3)> c2 = %Complex{re: 3, im: 4} | |
%Complex{im: 4, re: 3} | |
iex(4)> Addition.+(c1, c2) | |
%Complex{im: 6, re: 4} | |
iex(5)> import Kernel, except: [+: 2] | |
nil | |
iex(6)> import Addition | |
nil | |
iex(7)> 5 + 6 | |
11 | |
iex(8)> c1 + c2 | |
%Complex{im: 6, re: 4} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment