npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@susisu/effects

v0.4.0

Published

Poor man's algebraic effects for TypeScript

Downloads

2

Readme

effects

Build Status

Poor man's algebraic effects for TypeScript

NOTE: This is an experimental package and not suitable for production use.

npm i @susisu/effects
# or
yarn add @susisu/effects

Motivation

Imagine translating "Either" monad in Haskell or Scala into TypeScript, for example.

In TypeScript, there is no do- or for-comprehension available in Haskell and Scala, so basically you need to write callbacks (continuations) explicitly to write monadic programs.

const parse = (str: string): Either<Error, number> => {
  const num = parseFloat(str);
  if (Number.isNaN(num)) {
    return left(new Error(`failed to parse: ${str}`));
  }
  return right(num);
};

const divide = (x: number, y: number): Either<Error, number> => {
  if (y === 0) {
    return left(new Error("division by zero"));
  }
  return right(x / y);
};

const r1 = parse("42").bind(x =>
  parse("2").bind(y =>
    divide(x, y)
  )
);
// r1 = Right(21)

const r2 = parse("42").bind(x =>
  parse("0").bind(y =>
    divide(x, y)
  )
);
// r2 = Left(Error("division by zero"))

This is relatively simple example and you may not feel it is bad, but when the code becomes larger and more complex, the callback hell emerges.

You may notice that this is like Promises before async/await. Yes, it is the same problem.

readFile("file1.txt").then(x =>
  readFile("file2.txt").then(y =>
    writeFile("file3.txt", x + y)
  )
);

Generators (coroutines) can help to solve this kind of problem. You can define a special function _do that deals with generators, and the same logic can be written in a more flat and readable way.

const r1 = _do(function* () {
  const x = yield parse("42");
  const y = yield parse("2");
  const q = yield divide(x, y);
  return q;
});

There was a library named co that does the same thing for Promises.

However, the solution using generators can not be typed well. In the above example, all of x, y, and q are of type any unless you write type annotations explicitly.

Fortunately, async/await are typed well, because it is a built-in feature of the language.

const x = await readFile("file1.txt");
const y = await readFile("file2.txt");
await writeFile("file3.txt", x + y);

But async/await is only for Promises, and any other monads cannot enjoy this.

effects tries to address this issue by providing an "alternative" to generators along with a framework of algebraic effects, allows you to write your logic in a flat and type-safe way.

const r1 = runExn(perform => {
  const x = perform(parse("42"));
  const y = perform(parse("2"));
  const q = perform(divide(x, y));
  return q;
});

What is this?

effects provides poor man's algebraic effects for TypeScript.

  • It allows you to write procedures that may perform some effects (side-effects, interruptions, reading and updateing state, async/await, etc.) in a concise way.
  • It can be typed, in contrast to the solution using generators.
  • It provides "open" definition of effects, which means you can define your own effects.

Examples

The full code of the example in the previous section is the following:

import { Action, raise, runExn } from "@susisu/effects";
 
const parse = (str: string): Action<"exn/raise", number> => perform => {
  const num = parseFloat(str);
  if (Number.isNaN(num)) {
    return perform(raise(new Error(`failed to parse: ${str}`)));
  }
  return num;
};

const divide = (x: number, y: number): Action<"exn/raise", number> => perform => {
  if (y === 0) {
    return perform(raise(new Error("division by zero")));
  }
  return x / y;
};

const r1 = runExn(perform => {
  const x = perform(parse("42"));
  const y = perform(parse("2"));
  const q = perform(divide(x, y));
  return q;
});
// r1 = { isErr: false, val: 21 }

const r2 = runExn(perform => {
  const x = perform(parse("42"));
  const y = perform(parse("0"));
  const q = perform(divide(x, y));
  return q;
});
// r2 = { isErr: true, err: Error("division by zero") }

You can find more examples in the examples/ directory.

How does it work?

Why generators (coroutines) can be used to flatten monadic codes is that, they can be paused and resumed, that is, continuations at any point of function can be obtained.

So how we can obtain continuations at any point of a usual function? The answer is, we cannot, but we don't need. The key idea is that a function should perform completely the same when called multiple times if it is pure.

When perform is called with an effect for the first time in a procedure, it throws the effect to exit the function. The thrown effect is caught by runEff, and it passes the effect to the corresponding handler, updates its internal state using the value received from the handler, and executes the procedure the again. At the second (or third or more) call, perform just returns the value received from the handler before, and proceeds to the next.

An effect handler can also stop the procedure by simply not resuming it, and runEff exits then.

Limitations

There are (currently) some technical limitations:

  • The kind of effects are simply string literal types, and can not take type arguments.

Acknowledgement

License

MIT License

Author

Susisu (GitHub, Twitter)