Skip to content

Instantly share code, notes, and snippets.

@blackode
Created February 17, 2017 04:55
Show Gist options
  • Select an option

  • Save blackode/08f9ca351ed979d7526625b0467f6ef7 to your computer and use it in GitHub Desktop.

Select an option

Save blackode/08f9ca351ed979d7526625b0467f6ef7 to your computer and use it in GitHub Desktop.
Defining Elixir Protocols

#Define a Protocol

A Protocol is a way to dispatch to a particular implementation of a function based on the type of the parameter.
The macros defprotocol and defimpl are used to define Protocols and Protocol implementations for different types in the following example.

defprotocol Triple do    
  def triple(input)  
end  

defimpl Triple, for: Integer do    
  def triple(int) do     
    int * 3   
  end  
end   

defimpl Triple, for: List do
  def triple(list) do
    list ++ list ++ list   
  end  
end 

Usage

Load the code into iex and execute

iex> Triple.triple(3) 
9
Triple.triple([1, 2])
[1, 2, 1, 2,1,2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment