Skip to content

Instantly share code, notes, and snippets.

@awn-git
Created January 25, 2017 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awn-git/8a850f1ea6e800f25c750a4114cf59fc to your computer and use it in GitHub Desktop.
Save awn-git/8a850f1ea6e800f25c750a4114cf59fc to your computer and use it in GitHub Desktop.
関数型プログラミング練習.js
(function() {
const show = (x) => {
console.log(x);
};
//総和
var arr = [1, 3, 5, 7, 9];
show(arr.reduce((x, y) => x + y));
//最大値
var arr1 = [1, 10, 4, 30, 2, 9];
show(arr1.reduce((x, y) => x > y ? x : y));
//最小値
var arr2 = [3, 5, 18, -2, 9, 1, -1];
show(arr2.reduce((x, y) => x > y ? y : x));
//加算
const add = (x) => (y) => x + y;
/*
次は'const add = (x) => (y) => x + y;'と等価
const add = (x) => (y) => {return x + y};
const add = function(x){
return function(y){
return x + y;
};
};
*/
let add2 = add(2);
show(add2(3));
show(add(5)(6));
//乗算
const mul = (x) => (y) => x * y;
show(mul(5)(6));
//論理演算
const T = true;
const F = false;
const and = (x) => (y) => x && y;
const or = (x) => (y) => x || y;
show(and(T)(F));
show(or(F)(T));
show(and(or(F)(F))(and(F)(T)));
const ln = (x) => Math.log(x);
const E = Math.E;
show(ln(E));
show(-ln(E ** (-3)));
//偶数の中の最大値
var arr3 = [10, 3, 4, 5, 21, 8, 9, 2];
const even = (x) => x % 2 === 0;
const max = (xs) => Math.max(...xs);
show(max(arr3.filter(even)));
//奇数の中の最小値
const odd = (x) => x % 2 === 1;
const min = (xs) => Math.min(...xs);
show(min(arr3.filter(odd)));
//pipe
const pipe = (fns) => (x) => fns.reduce((v, f) => f(v), x);
let op = pipe([add(3),mul(2),add(5),mul(1),add(1),mul(7)]);
show(op(0));
show(op(1));
show(op(3));
show(pipe([add(1),mul(2),add(3),mul(4)])(1));
return;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment