Appendix A: Essential Functions Support

In this appendix, you’ll find some basic JavaScript implementations of various functions
described in the book. Keep in mind that these implementations may not be the fastest or the
most efficient implementation out there; they solely serve an educational purpose.

In order to find functions that are more production-ready, have a peak at
ramda, lodash, or folktale.

Note that some functions also refer to algebraic structures defined in the Appendix B

always

  1. // always :: a -> b -> a
  2. const always = curry((a, b) => a);

compose

  1. // compose :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
  2. function compose(...fns) {
  3. const n = fns.length;
  4. return function $compose(...args) {
  5. let $args = args;
  6. for (let i = n - 1; i >= 0; i -= 1) {
  7. $args = [fns[i].call(null, ...$args)];
  8. }
  9. return $args[0];
  10. };
  11. }

curry

  1. // curry :: ((a, b, ...) -> c) -> a -> b -> ... -> c
  2. function curry(fn) {
  3. const arity = fn.length;
  4. return function $curry(...args) {
  5. if (args.length < arity) {
  6. return $curry.bind(null, ...args);
  7. }
  8. return fn.call(null, ...args);
  9. };
  10. }

either

  1. // either :: (a -> c) -> (b -> c) -> Either a b -> c
  2. const either = curry((f, g, e) => {
  3. if (e.isLeft) {
  4. return f(e.$value);
  5. }
  6. return g(e.$value);
  7. });

identity

  1. // identity :: x -> x
  2. const identity = x => x;

inspect

  1. // inspect :: a -> String
  2. function inspect(x) {
  3. if (x && typeof x.inspect === 'function') {
  4. return x.inspect();
  5. }
  6. function inspectFn(f) {
  7. return f.name ? f.name : f.toString();
  8. }
  9. function inspectTerm(t) {
  10. switch (typeof t) {
  11. case 'string':
  12. return `'${t}'`;
  13. case 'object': {
  14. const ts = Object.keys(t).map(k => [k, inspect(t[k])]);
  15. return `{${ts.map(kv => kv.join(': ')).join(', ')}}`;
  16. }
  17. default:
  18. return String(t);
  19. }
  20. }
  21. function inspectArgs(args) {
  22. return Array.isArray(args) ? `[${args.map(inspect).join(', ')}]` : inspectTerm(args);
  23. }
  24. return (typeof x === 'function') ? inspectFn(x) : inspectArgs(x);
  25. }

left

  1. // left :: a -> Either a b
  2. const left = a => new Left(a);

liftA*

  1. // liftA2 :: (Applicative f) => (a1 -> a2 -> b) -> f a1 -> f a2 -> f b
  2. const liftA2 = curry((fn, a1, a2) => a1.map(fn).ap(a2));
  1. // liftA3 :: (Applicative f) => (a1 -> a2 -> a3 -> b) -> f a1 -> f a2 -> f a3 -> f b
  2. const liftA3 = curry((fn, a1, a2, a3) => a1.map(fn).ap(a2).ap(a3));

maybe

  1. // maybe :: b -> (a -> b) -> Maybe a -> b
  2. const maybe = curry((v, f, m) => {
  3. if (m.isNothing) {
  4. return v;
  5. }
  6. return f(m.$value);
  7. });

nothing

  1. // nothing :: () -> Maybe a
  2. const nothing = () => Maybe.of(null);

reject

  1. // reject :: a -> Task a b
  2. const reject = a => Task.rejected(a);