0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

純粋関数って何?

Posted at

定義

以下の2つの条件を満たす関数

1.同じ入力→「必ず」同じ出力を返す
2.副作用がない

純粋関数の例

function add(a, b) {
  return a + b;
}

1.同じ入力→「必ず」同じ出力を返す

ここで言う、入力とは引数のことである。
下記のように、引数として2,3を渡せば「必ず」5が返ってくる。
これで1の条件はクリアだ。

const result = add(2,3)
console.log(result);
// 5

2.副作用がない

副作用とは、関数の外の状態を変更したり、外の状態に依存したりすることである。
では、純粋関数ではない例を見ながら以下の2つの意味について考えてみよう。
①関数の外の状態を変更する
②外の状態に依存する

純粋関数ではない例

let count = 0;

function increment() {
  count++;
  return count;
}

関数incrementは変数countをインクリメントしているが、countはincrementに渡ってきたものではなくて、incrementの外で定義されたものだ。
よって関数の外の状態を変更している。

また、countの値が、5であればincrementは6を返すし、9であれば10を返す。
つまり、関数の「外の状態」に依存している。
よって副作用があると言える。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?