1

Associativity is a desirable property and quite common for many operations in FP. Now I was wondering if an impure function can interfere with it. The only example I found isn't really convincing, because I'm not sure if nullary functions count as proper functions (riegorously speaking) and additionally, the example looks rather contrived.

The following is written in JS but is hopefully self-explanatory:

// function composition
const comp = f => g => x => f(g(x));

const foo = () => 1;
const bar = () => Math.round(Math.random() * 100);

// Set functor (ignore the hideous implementation)
const map = f => s => {
  const r = new Set();
  s.forEach(x => r.add(f(x)));
  return r;
};

const lhs = map(comp(bar) (foo));
const rhs = comp(map(bar)) (map(foo));

const set1 = lhs(new Set([1, 2, 3]));
const set2 = rhs(new Set([1, 2, 3]));

console.log(Array.from(set1)); // yields an array filled with up to three random integers
console.log(Array.from(set2)); // yields an array filled with a single random integer

I'm not sure whether this example can be considered as evidence. Are there more convincing examples?

  • I am thinking someone with a background in Category Theory and Computer Science would be able to easily answer this. Perhaps you should move the question to [Math](https://math.stackexchange.com/) or [Computer Science](https://cs.stackexchange.com/). My guess is yes but I would like to see a proof for this this an that is beyond my skill set. – Guy Coder Oct 29 '20 at 09:26
  • I tried to come up with another example or to track down one online, without any results though. There probably is no relation between both properties whatsoever. –  Oct 29 '20 at 19:19
  • 1
    I am thinking that an exception or a side effect like printing to a terminal could be used for an example. When printing debug messages from multitasking code the order of the messages should be in time order, but some times they come in batches grouped by a task and are out of time sequence. – Guy Coder Oct 30 '20 at 10:20
  • Agreed, I guess. Am still a bit confused, though. Race conditions take place in Javascropt event loop as well - in the context of async computations. I think mutations as a class of side effects give rise to race conditions and render more functions non-idempotent. But they don't interfere with associativity/commutativity directly. –  Oct 30 '20 at 13:15

0 Answers0