Help us understand the problem. What is going on with this article?

# Elixir と Ruby のsumの比較

More than 3 years have passed since last update.

まだ、関数型プログラミングの記述、特に再帰には慣れていない。
でも、再帰＆パターンマッチが含まれているので理解するべき。

## Ruby

sum.rb
```def sum(n)
result = 0
(1..n).each do |n|
result = result + n
end
result
end

n = 5
puts sum(n)

# => 15
```

## Elixir

sum.exs
```defmodule Sum do
def sum(0), do: 0
def sum(n), do: n + sum(n - 1)
end

n = 5
IO.puts(Sum.sum(n))

# => 15
```

または、わかりやすく書くと

sum.exs
```defmodule Sum do
def sum(0) do
0
end
def sum(n) do
n + sum(n - 1)
end
end

n = 5
IO.puts(Sum.sum(n))

# => 15
```

### ※追記

ちなみに、`Elixir` には標準でリストを`sum`する関数は`Enum`に存在します。

sum.exs
```n = 5
IO.puts(Enum.sum(1..n))

# => 15
```
Web System Engineer 元フリーランスの金融系SE(Java/Swift/Ruby/Python/JS/AS3/php/J2EE/Rails/Oracle/MySQL) 趣味:Web開発/アイスホッケー/フットサル/野球/スキー/Ukulele
http://www.whoocus.com/blog/
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away