Skip to content

Instantly share code, notes, and snippets.

@sezemiadmin
Last active August 20, 2018 12:49
Show Gist options
  • Save sezemiadmin/c3a2eda66ce3c8dd0f89d0fb40017591 to your computer and use it in GitHub Desktop.
Save sezemiadmin/c3a2eda66ce3c8dd0f89d0fb40017591 to your computer and use it in GitHub Desktop.
関数型プログラミングを知る のサンプルコード
-- リスト内の要素をすべて負の値に変換する(関数合成)
-- Haskellでは.で繋げる
Prelude> map (negate . abs) [1, -2, 3] --[-1, -2, -3]
-- 3つの値を引数として受け取り、すべての値を掛け合わせた数を返す triplet 関数
Prelude> triplet x y z = x * y * z
Prelude> triplet 2 3 4 -- 24
-- 部分適用や再利用も可能
-- triplet 2 3 --6で固定
t1 = triplet 2 3 -- 最初の2つの引数のみ部分適用
t1 5 -- 残りの引数zに5を適用 30
t1 10 -- 残りの引数zに10を適用 60
List<Employee> employeeList = dao.findAll();
List<String> nameList = new ArrayList<>();
for (Employee employee : employeeList) {
if (employee.getDepartment().equals("Sales") &&
employee.getSalary() > 3000) {
nameList.add(employee.getName());
}
}
/* for文やif文を使わない*/
List<String> nameList = dao.findAll().stream() // stringメソッド
.filter(e -> e.getDepartment().equals("Sales")) // 部署が営業部で
.filter(e -> e.getSalary() > 3000) // 給与が3000よりも大きい
.map(Employee::getName) // 従業員名を抽出して
.collect(Collectors.toList()); // 新たなリストを作成
Prelude> double x = x * 2 -- 引数で受け取った値を2倍する関数
Prelude> triple x = x * 3 -- 引数で受け取った値を3倍する関数
Prelude> op x f = f x -- 値と関数を引数に取り、その関数に値を適用する高階関数
Prelude> op 2 double -- 4
Prelude> op 2 triple -- 6
Prelude> op 2 (\x -> x + 1) -- 引数に無名関数(ラムダ式)を利用 3
int factorial(int n) {
if(n == 0) {
return 1;
}
return n * factorial(n - 1);
}
(\x y -> x + y) 1 2 -- 3
int sum(int a, int b) {
return a + b;
}
int a;
int b;
int sum() {
return a + b; // NOT referencial transparency
}
factorial :: Int -> Int --型定義もできる
{-
関数定義 引数が0の場合1を返す
-}
factorial 0 = 1 --関数定義 引数が0の場合1を返す
factorial n = n * factorial (n - 1) --0以外の整数を受け取ったら factorial 関数を返す
-- 引数に () は要らない
-- return文を書かない
sum x y = x + y
sum 1 2 -- 3
int c;
int sum(int a, int b) {
c = a; // side-effect
int result = a + b;
print(result); // side-effect
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment