Skip to content

Instantly share code, notes, and snippets.

@dreamingblackcat
Last active August 29, 2015 14:11
Show Gist options
  • Save dreamingblackcat/ff07058a78122446d104 to your computer and use it in GitHub Desktop.
Save dreamingblackcat/ff07058a78122446d104 to your computer and use it in GitHub Desktop.
An elixir module for defining power function without using multiplication operator.
defmodule Compute do
def twoPlus(num), do: 2+num
def twoTimes(0), do: 0
def twoTimes(num) when num < 0, do: -twoTimes(-num)
def twoTimes(num) when num > 0, do: twoPlus(twoTimes(num-1))
def twoPower(0), do: 1
def twoPower(num) when num > 0, do: twoTimes(twoPower(num-1))
def twoPower(num) when num < 0, do: "1/#{twoPower(-num)}" #I just print the rational number style string :D
end
IO.puts Compute.twoPlus(3) #=> 5
IO.puts Compute.twoTimes(-4) #=> -8
IO.puts Compute.twoTimes(4) #=> 8
IO.puts Compute.twoPower(-8) #=> 1/256
IO.puts Compute.twoPower(8) #=> 256
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment