Last active
August 29, 2015 14:11
-
-
Save dreamingblackcat/ff07058a78122446d104 to your computer and use it in GitHub Desktop.
An elixir module for defining power function without using multiplication operator.
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
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