Skip to content

Instantly share code, notes, and snippets.

@YSMull
Created December 28, 2018 03:39
Show Gist options
  • Save YSMull/bb678c7b85294c29e07f0069fb49183f to your computer and use it in GitHub Desktop.
Save YSMull/bb678c7b85294c29e07f0069fb49183f to your computer and use it in GitHub Desktop.
Funtion as Applicative in JavaScript
let _ = require('lodash');
let pure = x => _ => x;
let ap = f => g => x => f(x)(g(x));
let add = a => b => a + b;
let multi = a => b => a * b;
let minus3 = a => b => c => a - b - c;
// (+) <*> (2*) $ 3 :---> (+ 3 (* 2 3)) = 9
console.log(ap(add)(multi(2))(3)); // 9
// minus3 <*> (2+) <*> (3*) $ 5 :---> 5 - (2+5) - (3*5) = -17
console.log(ap(ap(minus3)(add(2)))(multi(3))(5)); // = -17
// 为了使用现有工具演示,以下两个函数的 f 暂时不克里化
let zipWith = f => xs => ys => _.zipWith(xs, ys, f);
let map = f => xs => xs.map(f);
// zipWith (*) <*> map (2+) $ [1,2,3] :---> zipWith (*) [1,2,3] (map (2+) [1,2,3]) = [3,8,15]
console.log(ap(zipWith((a,b) => a*b))(map(a => 2+a))([1,2,3])); // [3,8,15]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment