Skip to content

NatTuck/methods-elixir

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Methods

Elixir needed method call syntax, so I added it.

  defmodule Rect do
    defstruct [width: 0, height: 0]

    def area(self) do
      self.width * self.height
    end
  end 

  defmodule Main do
    use Methods

    def main do
      r1 = %Rect{width: 10, height: 10}
      area = r1..area()
    end
  end

Yes, I stole the ".." operator. It still works for constructing ranges as long as you don't put a function call on the right side.

I'd rather have stolen the "." operator, but the compiler won't let me. I guess once everyone agrees this is a good idea it can get added as improved Elixir syntax.

Wait, why?

Method syntax has two big wins over just calling functions:

  • Dynamic dispatch. You can loop over a list of shapes and call "shape..area()" on each one. For squares, you get Square.area(), for circles you get Circle.area().
  • Reduced verbosity or namespace pollution. You don't need to chose between "import Square" and typing "Square.area", structs already know where their methods are.

There are disadvantages:

  • Dynamic dispatch is slower and can't be optimized, especially since the compiler and runtime don't expect it.
  • Error messages might be terrible.
  • This particular implementation breaks constructing perfectly reasonable ranges like "1..sqrt(n)".

Installation

def deps do
  [
    {:methods, "~> 0.1.0"}
  ]
end

Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/methods.

About

Add method calls to elixir.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages