DEV Community

Iven Marquardt
Iven Marquardt

Posted on

f is not the same as x => f(x)

f is not the same as x => f(x) when it comes to evaluation in a strictly evaluated language like Javascript. The latter renders a function slightly more lazy:

const mapFold = f => acc => ix => {
  for (let [i, x] of ix)
    acc = f(acc) (x);

  return acc;
};

const arrSnoc = xs => x =>
  (xs.push(x), xs);

const mapToArr =
  mapFold(arrSnoc) ([]);

const mapToArr_ = ix =>
//                ^^
  mapFold(arrSnoc) ([]) (ix);
//                      ^^^^

const foo = new Map([[0, "foo"], [1, "bar"], [2, "baz"]]);

mapToArr(foo);
mapToArr_(foo);

mapToArr(foo); // ["foo", "bar", "baz", "foo", "bar", "baz"]
mapToArr_(foo); // ["foo", "bar", "baz"]

mapToArr gets a fesh array as accumulator each time it is called and hence keeps the side effect caused by arrSnoc local. Adding redundant lambda abstractions to a derived function is called eta abstraction and the opposite operation eta reduction.

Read more on lazy evaluation.

Top comments (0)