Michael
Michael

Reputation: 521

How to use the Free Monad

I have been looking into the Free monad because I have read that a use case for it is to do logging in a side-effect free way.

I am attempting to do this in JavaScript with the Monet library.

However the documentation is lacking and I do not understand the Free monad well enough figure it out on my own(I have been trying).

I have looked into the Haskell implementation, but I do not read Haskell well and the methods do not appear to be named the same, so I am having trouble.

Any chance someone can give me a simple example of how the Free monad works in either JavaScript or pseudo code that matches the above library?

I feel like if I can see a complete example, I will understand better.

Here are the unit tests from the Monet library: https://github.com/monet/monet.js/blob/develop/test/free-spec.js

But they don't help me much (because they are tests).

Upvotes: 4

Views: 1066

Answers (1)

David Braun
David Braun

Reputation: 5899

Doing logging in a side-effect free way is usually done with the Writer Monad:

const compose = (f, g) => value => f(g(value));

const Writer = ({ log = [], value }) => ({
  flatMap: func => {
    const mapped = func(value);

    return Writer({
      log: log.concat(mapped.log),
      value: mapped.value
    });
  },

  log,
  value
});

Writer.of = value => Writer({ value });

Writer.log = entry => value => Writer({ log: [entry], value });

const { log, value } = Writer.of(-42.5)
  .flatMap(compose(Writer.of, Math.abs))
  .flatMap(Writer.log(`abs`))
  .flatMap(compose(Writer.of, Math.floor))
  .flatMap(Writer.log(`floor`));

console.log({ log, value })

Upvotes: 0

Related Questions