Created
July 25, 2013 13:39
-
-
Save spikegrobstein/6079721 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
defmodule Math do | |
def pow( num, power ) do | |
_pow num, power, 1 | |
end | |
def _pow( num, 0, acc ) do | |
acc | |
end | |
def _pow( num, power, acc ) when power > 0 do | |
_pow( num, power - 1, acc * num) | |
end | |
end | |
defmodule Convert do | |
defmodule Binary do | |
import Enum | |
import Math | |
def to( value ) when value > 0 do | |
_to value, [] | |
end | |
def _to( 0, list ) do | |
list | |
end | |
def _to( value, list ) when value > 0 do | |
_to div(value, 2), [ rem(value, 2) | list ] | |
end | |
def from( value ) when is_list( value ) do | |
_from Enum.reverse( value ), 0, 0 | |
end | |
def _from( [], power, acc ) do | |
acc | |
end | |
def _from( [ v | tail ], power, acc ) do | |
_from tail, power + 1, acc + ( v * pow(2, power) ) | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment