Guest User

Untitled

a guest
Dec 17th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. // `fix` is an Y-combinator implementation (recursive calls in lambda calculus):
  2. // Y = \f -> (\x -> f (x x))(\x -> f (x x))
  3.  
  4. // fix :: (a -> a) -> a
  5. const fix = f => (x => f(y => (x(x))(y)))(x => f(y => (x(x))(y)));
  6.  
  7. // Generator function. Inner signature should correspond to actual function interface.
  8. // mapgen :: ((a -> b) -> [a] -> [b]) -> (a -> b) -> [a] -> [b]
  9. const mapgen = map => f => list => list.length === 0 ? [] : [f(list[0])].concat(map(f)(list.slice(1)));
  10.  
  11. // Memoization of a function of 1 argument. For functions of more arguments explicit work with `arguments` needed.
  12. // memoize :: (a -> b) -> a -> b
  13. const memoize = fn => x => {
  14. const hash = x === Object(x) ? JSON.stringify(x) : x.toString();
  15. fn.memoize || (fn.memoize = {});
  16. return (hash in fn.memoize) ? fn.memoize[hash] : (fn.memoize[hash] = fn(x));
  17. };
  18.  
  19. // map :: (a -> b) -> [a] -> [b]
  20. const map = fix(memoize(mapgen));
Add Comment
Please, Sign In to add comment