r/functionalprogramming • u/jcastroarnaud • Mar 30 '26
Question How to create a Result monad in JavaScript?
Does anyone know of tips to create, or a good implementation of, a Result monad in JavaScript (not TypeScript), that I can adapt for my own?
I use JavaScript in my personal projects, and I want to have a Result monad as part of a recursive-descent parser: the intention is to "carry back" a failed match or a parsing error, without throwing exceptions around.
I found a few implementations of Result in the wild, but they differ greatly in design and methods, some are disguised Either or Maybe monads, and some are in TypeScript instead of JavaScript.
I want to implement Result myself, instead of using a npm package, and want to make it simple: constructor, map, getters for value and error, and little else. For reference, here are the Identity and Maybe monads I implemented:
const Tag = {
Nothing: "Nothing",
Just: "Just"
};
class Monad {
#v;
static of(value) {
return new Monad(value);
}
constructor(value) {
this.#v = value;
}
map(fn) {
return Monad.of(fn(this.#v));
}
get value() { return this.#v; }
}
class Maybe extends Monad {
#t = Tag.Nothing;
static of(value) {
if (value instanceof Monad) {
/* Unwrapping monad-in-monad. */
return Maybe.of(value.value);
} else if (value === null || value === undefined) {
return new Maybe(Tag.Nothing, null);
} else {
return new Maybe(Tag.Just, value);
}
}
constructor(tag, value) {
super(value);
this.#t = tag;
}
get isJust() { return this.#t === Tag.Just; }
get isNothing() { return this.#t === Tag.Nothing; }
map(fn) {
if (this.isJust) {
return Maybe.of(fn(this.value));
} else if (this.isNothing) {
return Nothing();
}
/* There is no else. */
}
// get value() é herdado de Monad.
}
const Nothing = () => Maybe.of(null);
const Just = (v) => Maybe.of(v);
7
u/Delta-9- Mar 30 '26
The most important thing is for your monadic types to conform to the three laws.
I also recommend adopting similar method names to what's used in Haskell or Rust, but that's personal preference. I implemented Result in Python and mostly stuck to Rust's naming conventions in hopes that anyone else reading my code might have at least passing familiarity with another very popular language.
Anyway, in my implementation, I found it was easiest to fit to the three laws by defining some methods in terms of each other. For example,
bindcan be justjoin ∘ map. Doing it this way helps because the three laws are all about functional composition, so building functions by composing functions all but guarantees the resulting functions are composable, too. It also saves a lot of boilerplate code, eg.bindis exactly the same thing asmapexcept for the additional flattening step ofjoin.One other thing I'd recommend: add a method that works like
mapbut returns the current wrapped value instead of the function's return value. I called thissequence, and I think Haskell has an operator for this (>>, maybe? It's probably in the link I shared above). This is very useful for inserting eg. aconsole.logcall into a long chain of calls tomapwithout having to break the chain to store the intermediate value in a variable or something. Anything that does some side effect and doesn't return anything can be composed with this method.3
u/Long_Investment7667 Mar 30 '26 edited Mar 30 '26
I would just check what typescript does and follow that pattern
typescript
JavaScript
3
u/AustinVelonaut Mar 30 '26
I don't have any JavaScript suggestions, but for a parser, you likely want a monad implementation that is a combination of a Maybe monad and a State monad (I call this MaybeState). The State part holds the current parser token position, possibly along with some other state such as errors, etc. The Maybe part is used to determine parser pass or fail. Backtracking would be implemented with an
altmethod, where the first parser in the alt is tried, and if it fails, state is rewound to the original state and the second parser is tried.5
u/sent1nel Mar 31 '26
Check fantasyland js
3
u/Massive-Squirrel-255 Mar 30 '26
only loosely relevant but here is one implementation of monads in a dynamically typed language. https://okmij.org/ftp/Scheme/monad-in-Scheme.html
see also
https://www.schemeworkshop.org/2005/03-sobel/03-sobel.pdf
3
u/_lazyLambda Mar 30 '26
Ive implemented them in C# and theres a reason the implementations vary greatly. The language was never set up for that.
Tbh it takes months to say hmm maybe I do this instead until youve finally learned each sucks in its own way.
Thats C# of course but the semantic issues you run into are gonna be roughly the same in any OOP designed language. The closest I got to something real was using the scope of a class to have subclasses.
I dont think people realize just yet how a functional compiler really means infinitely more degrees of freedom which really comes through when you to build the higher kinded sum type of Either in a language that has no concept of sum types or higher kindedness. And you learn that NO higher kindedness is not the same thing as a polymorphic class.
3
u/[deleted] Mar 30 '26
[removed] — view removed comment