Created
June 17, 2016 15:30
-
-
Save macrat/6e0b1db7c343f9ee43279fd8d9dd12c1 to your computer and use it in GitHub Desktop.
インクリメントとデクリメントで四則演算 with Elixir
This file contains hidden or 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 Main do | |
def inc x do | |
x + 1 | |
end | |
def dec x do | |
x - 1 | |
end | |
defp minus(x, y) when x < 0 do | |
minus inc(x), inc(y) | |
end | |
defp minus(x, y) when x > 0 do | |
minus dec(x), dec(y) | |
end | |
defp minus _, y do | |
y | |
end | |
def minus x do | |
minus x, 0 | |
end | |
def add x, 0 do | |
x | |
end | |
def add(x, y) when y < 0 do | |
minus add minus(x), minus(y) | |
end | |
def add x, y do | |
add inc(x), dec(y) | |
end | |
def sub x, y do | |
add x, minus(y) | |
end | |
def sum [] do | |
0 | |
end | |
def sum [x | xs] do | |
add x, sum xs | |
end | |
def dup _, 0 do | |
[] | |
end | |
def dup x, n do | |
[x | dup(x, dec n)] | |
end | |
def absolute(x) when x < 0 do | |
minus x | |
end | |
def absolute x do | |
x | |
end | |
def times(x, y) when y < 0 do | |
times minus(x), minus(y) | |
end | |
def times x, y do | |
sum dup x, y | |
end | |
def divide(x, y) when x < 0 and y < 0 do | |
divide minus(x), minus(y) | |
end | |
def divide(x, y) when x < 0 or y < 0 do | |
minus divide absolute(x), absolute(y) | |
end | |
def divide(x, y) when x < y do | |
0 | |
end | |
def divide x, y do | |
inc divide sub(x, y), y | |
end | |
end | |
IO.puts Main.divide -10, -3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment