LoginSignup
1
0

More than 1 year has passed since last update.

paiza.ioでelixir その37

Posted at

概要

paiza.ioでelixirやってみた。
when使ってみた。パターンマッチングと再帰入ってる。

サンプルコード

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.add -10, -3
IO.puts Main.sub -10, -3
IO.puts Main.divide -10, -3
IO.puts Main.times -10, -3


実行結果

-13
-7
3
30

成果物

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0