@b-jones-rfd/func-help
v0.7.1
Published
Haskell-style functional helpers for TypeScript: Either, Except, IO, AsyncIO, State, Reader and do notation.
Maintainers
Readme
func-help
Haskell-style functional helpers for TypeScript, as classes: Either, Except, IO, AsyncIO, State, Reader, and do notation over generators (Either.do, IO.do, …). Each one is a value that describes a computation: failure is carried as data instead of thrown, side effects are held back until you call run(), state is threaded through a chain instead of mutated, and configuration is read from an environment supplied once. Everything is chained with map and bind, so the same habits work across all of them. Names follow Haskell's base and mtl (Either, State.get/put/modify/gets, eval/exec, Reader.ask/asks/local); where a name differs, the API tables below give the Haskell name. For The Elm Architecture as plain data (Cmd, Sub, Task, Maybe, Result), see @b-jones-rfd/tea-set; func-help keeps to classes with methods.
Requirements
- Node.js 22.12 or later. The package is ESM only; from 22.12, CommonJS projects can
require()it too. - Browsers with Baseline Widely available features (supported in Chrome, Edge, Firefox and Safari for at least 30 months).
- TypeScript (optional): any release from the last two years.
- Nothing else. There are no runtime dependencies.
Installation
npm i @b-jones-rfd/func-help
# or
pnpm add @b-jones-rfd/func-help
# or
yarn add @b-jones-rfd/func-helpQuick start
import { Either, IO } from '@b-jones-rfd/func-help'
const parseNumber = (s: string): Either<string, number> => {
const n = Number.parseFloat(s)
return Number.isNaN(n)
? Either.left(`'${s}' is not a number`)
: Either.right(n)
}
const reciprocal = (n: number): Either<string, number> =>
n === 0 ? Either.left('division by zero') : Either.right(1 / n)
const describe = (input: string): string =>
parseNumber(input)
.bind(reciprocal)
.fold(
(err) => `Error: ${err}`,
(value) => `Reciprocal is ${value}`
)
// Nothing is printed yet: an IO only describes the effect.
const program: IO<void> = IO.from(() => describe('10'))
.tap((message) => console.log(message)) // Reciprocal is 0.1
.bind(() => IO.from(() => console.log(describe('abc')))) // Error: 'abc' is not a number
program.run() // now both lines are printedThe same program is in examples/basic.ts. The examples are type-checked with the package but not published.
Usage
Every type here is a value that describes a computation. map(f) transforms the value inside; bind(f) (Haskell's >>=) runs the next step, which returns another value of the same type, and joins the two. map obeys the functor laws and bind the monad laws, so refactoring a chain does not change its result.
The types split in two:
- Eager:
EitherandExcept. Each holds a result that already exists, a success or a failure. A failure short-circuits the rest of a chain, and the functions you pass run at the call that receives them. So a recursive loop throughbindon either one is plain JavaScript recursion, limited by the call stack like any other. - Lazy:
IO,AsyncIO,StateandReader. Each holds a recipe. Building and chaining one runs nothing; your functions run only when you callrun()(or, forState,eval()orexec(); forReader,run(env)), and they run again on every call.IO,StateandReaderrun a chain of any depth without growing the stack, so a long chain or a recursive loop (retrying, polling, paging) is limited by memory, not the call stack.
All of them implement the Monad<T> interface (map and bind), which is what Do builds on.
Either
Either<L, R> is a Left holding an L, usually an error, or a Right holding an R, the success. map and bind work on the Right; a Left passes through untouched. Build one with left, right or of, convert with fromNullable and tryCatch, and get a plain value back with fold, match or getOrElse.
import { Either } from '@b-jones-rfd/func-help'
const readPort = (setting: string | undefined): number =>
Either.fromNullable(setting, () => 'PORT is not set')
.map(Number)
.getOrElse(() => 3000)
readPort(undefined) // 3000
// Without onError, the Left is whatever was thrown, typed unknown.
const raw: Either<unknown, unknown> = Either.tryCatch((): unknown =>
JSON.parse('{ not json')
)
// With onError, you choose the Left type.
const parsed: Either<string, unknown> = Either.tryCatch(
(): unknown => JSON.parse('{ not json'),
(e) => (e instanceof Error ? e.message : String(e))
)
const message = parsed.match({
left: (err: string) => `Invalid JSON: ${err}`,
right: (value: unknown) => `Parsed ${typeof value}`,
})isLeft() and isRight() are type guards, and swap() exchanges the two sides.
The failure side has its own operations. mapLeft changes the Left and bimap maps both sides at once. catchError recovers from a Left with a handler that returns another Either of the same Right type. tap runs a side effect on a Right and keeps the value.
import { Either } from '@b-jones-rfd/func-help'
const parsePort = (s: string): Either<string, number> =>
/^\d+$/.test(s)
? Either.right(Number(s))
: Either.left(`'${s}' is not a port`)
const port: Either<Error, number> = parsePort('http')
.catchError(() => parsePort('8080')) // fall back to a default
.mapLeft((message) => new Error(message))
.tap((n) => console.log(`using port ${n}`))Where a throw surfaces: a function you pass to map, bind, tap, mapLeft, bimap, catchError, fold, match, getOrElse or fromNullable that throws propagates synchronously from that call; it is not captured as a Left. Only tryCatch captures throws, and only from effect: if onError throws, that error propagates from tryCatch. A function you pass to Either.traverse that throws propagates from that call too.
Except
Except<A> is Either with the failure fixed to Error: a failure holding an Error, or a success holding an A. Build one with ok, failed or of, and get a plain value back with fold, match (which takes { failed, ok }) or getOrElse.
import { Except } from '@b-jones-rfd/func-help'
const parsePort = (s: string): Except<number> => {
const n = Number.parseInt(s, 10)
return Number.isNaN(n)
? Except.failed(new Error(`'${s}' is not a port`))
: Except.ok(n)
}
const label = parsePort('8080').match({
failed: (e) => `Error: ${e.message}`,
ok: (port) => `Listening on ${port}`,
})
// A thrown value that is not an Error is wrapped in one, with the original as its cause.
const config = Except.tryCatch((): unknown => JSON.parse('{ not json'))
config.isError() // truemapError changes the Error (to another Error), catchError recovers from a failure with a handler that returns another Except of the same type, and tap runs a side effect on a success. Except.fromEither turns an Either whose Left is an Error into an Except, and toEither() goes back; from an Either, mapLeft can change the error to a type that isn't an Error, which mapError can't.
import { Either, Except } from '@b-jones-rfd/func-help'
const port: Except<number> = Except.fromEither(
Either.left<string, number>('PORT is not set').mapLeft((m) => new Error(m))
)
.mapError((e) => new Error(`loading config: ${e.message}`, { cause: e }))
.catchError(() => Except.ok(3000))
const reason: Either<string, number> = Except.failed<number>(new Error('bad'))
.toEither()
.mapLeft((e) => e.message)Where a throw surfaces: the same as Either. A function you pass to map, bind, tap, mapError, catchError, fold, match, getOrElse or fromNullable that throws propagates from that call and is not captured as a failure. Only tryCatch captures throws, and only from effect. A function you pass to Except.traverse that throws propagates from that call too.
IO
IO<A> wraps a synchronous side effect. IO.from(effect) holds the effect without running it, IO.of(value) lifts a plain value, and tap runs an extra effect while keeping the value. Nothing runs until run(), and each run() runs the whole chain again.
import { IO } from '@b-jones-rfd/func-help'
const now: IO<Date> = IO.from(() => new Date())
const log = (msg: string): IO<void> => IO.from(() => console.log(msg))
const showTime: IO<void> = now.map((date) => date.toISOString()).bind(log)
showTime.run() // prints the time
showTime.run() // prints it again, with a new timeattempt() turns a throw back into data: it gives an IO<Except<A>> whose run() never throws.
import { IO } from '@b-jones-rfd/func-help'
const readConfig = IO.from((): string => {
throw new Error('no config file')
})
readConfig
.attempt()
.run()
.fold(
(e) => `failed: ${e.message}`,
(text) => text
) // 'failed: no config file'Where a throw surfaces: a throw in the effect or in a function you pass to map, bind or tap is thrown from run(), not from the call that built the IO. After attempt(), a throw anywhere earlier in the chain becomes a failed Except instead, and a non-Error is wrapped as Except.tryCatch wraps it. A function chained after attempt() throws from run() as usual, and a promise an IO returns is not awaited, so its rejection is not captured; use AsyncIO for that. For IO.traverse and IO.sequence, a throw from f or from an item is thrown from run(), and the items after it don't run.
AsyncIO
AsyncIO<A> is IO for asynchronous effects: AsyncIO.from(effect) holds a function that returns a promise, and run() returns a Promise<A>. Each step waits for the one before it.
import { AsyncIO } from '@b-jones-rfd/func-help'
type User = { id: string; name: string }
const loadUser = (id: string): AsyncIO<User> =>
AsyncIO.from(async () => ({ id, name: 'Ada' }))
const greeting: AsyncIO<string> = loadUser('1')
.map((user) => `Hello, ${user.name}`)
.tap((text) => console.log(text))
await greeting.run() // 'Hello, Ada'
// Even a synchronous throw becomes a rejection: run() itself never throws.
const broken = AsyncIO.from<number>(() => {
throw new Error('boom')
})
await broken.run().catch((e: unknown) => console.error(e))AsyncIO.fromIO(io) lifts an IO, which runs each time the AsyncIO runs. AsyncIO.fromExcept(except) lifts an Except: a failure rejects with its Error itself. attempt() turns a rejection back into data, giving an AsyncIO<Except<A>> whose run() never rejects.
import { AsyncIO } from '@b-jones-rfd/func-help'
const fetchUser = AsyncIO.from((): Promise<string> =>
Promise.reject(new Error('offline'))
)
const result = await fetchUser.attempt().run()
result.fold(
(e) => `failed: ${e.message}`,
(name) => name
) // 'failed: offline'Where a throw surfaces: every error, including a synchronous throw from the from effect, a throw from an IO lifted with fromIO, and a throw in a function you pass to map, bind or tap, rejects the promise run() returns. run() never throws. After attempt(), every such error becomes a failed Except instead (a non-Error is wrapped as Except.tryCatch wraps it), and a function chained after attempt() rejects as usual. For the many-value statics, a throw from f or a rejected item rejects run(): traverse and sequence don't start the items after it, and mapConcurrently and concurrently reject with the first rejection in time while the rest keep running.
Moving between types
The types convert into one another along one route, from synchronous and pure to asynchronous:
EithertoExcept:mapLefttheLeftto anError, thenExcept.fromEither.toEither()goes back.IOtoAsyncIO:AsyncIO.fromIO.ExcepttoAsyncIO:AsyncIO.fromExcept; a failure rejects with itsError.- Back to data:
attempt()on anIOorAsyncIOturns a throw or rejection into a failedExcept.
There is no AsyncIO.fromEither, because a Left need not be an Error, and a promise rejected with something else loses its stack. Go through Except. A promise value lifted with fromIO or fromExcept is awaited, as AsyncIO.of awaits one, but the type still says AsyncIO<Promise<…>>; lift an IO<Promise<A>> with AsyncIO.from(() => io.run()).
examples/pipeline.ts runs a pipeline through all four: an IO reads a setting, an Either parses it, Except carries the error into AsyncIO, and attempt folds the outcome into a message.
Combining many values
Every type has traverse(items, f) and sequence(items) as statics (Haskell's traverse and sequence). traverse applies f to each item (f also gets the index, as with Array#map) and collects the results into one value of the type; sequence does the same for an array that already holds the values. An empty array gives [], results keep input order, and traverse(xs, f) is sequence(xs.map(f)).
import { Either, Except, IO } from '@b-jones-rfd/func-help'
const parsePort = (s: string): Either<string, number> =>
/^\d+$/.test(s)
? Either.right(Number(s))
: Either.left(`'${s}' is not a port`)
Either.traverse(['80', '443'], parsePort) // Right([80, 443])
Either.traverse(['80', 'http'], parsePort) // Left("'http' is not a port")
// A tuple stays a tuple, typed per position, with no `as const`.
const address = Except.sequence([Except.ok('localhost'), Except.ok(8080)])
// Except<[string, number]>
const reads = IO.sequence([IO.from(() => 'a'), IO.from(() => 1)])
reads.run() // ['a', 1]; nothing ran until hereEitherandExceptstop at the first failure, andfis not called for the items after it.Either.sequence's Left is the union of the items' Left types.IOandAsyncIOare lazy: nothing runs, andfis not called, untilrun(), and everyrun()runs every item again. The array is copied when the value is built.sequencekeeps a tuple's shape:[Either<string, number>, Either<HostError, string>]givesEither<string | HostError, [number, string]>. An array gives an array. The result is a new, mutable array.
AsyncIO.traverse and AsyncIO.sequence run the items one after another: each starts only after the one before resolves, and the first rejection stops the rest. To run them at the same time, use AsyncIO.mapConcurrently(items, f) and AsyncIO.concurrently(items) (from Haskell's async package):
import { AsyncIO } from '@b-jones-rfd/func-help'
const loadUser = AsyncIO.from(() => Promise.resolve({ name: 'Ada' }))
const loadTheme = AsyncIO.from(() => Promise.resolve('dark'))
const [user, theme] = await AsyncIO.concurrently([loadUser, loadTheme]).run()- Every item starts at once, with no limit, and the results keep input order, not the order they finish.
- The first rejection in time rejects
run(), as withPromise.all. The others keep running, becauseAsyncIOhas no cancellation, and their rejections are observed, so none goes unhandled. A synchronous throw fromfcounts as that item's rejection. - Haskell's
concurrentlytakes two actions and returns a pair; this one takes any number, typed per position.
examples/many.ts runs each of these, and shows traverse taking the sum of the delays where mapConcurrently takes about the longest.
State
State<S, A> is a computation that reads and updates a state of type S and produces an A. State.get reads the state, State.put replaces it, State.modify transforms it and State.gets projects a value from it. Nothing runs until you give it a starting state: run(initial) returns the pair [result, finalState], eval(initial) the result only and exec(initial) the final state only.
import { State } from '@b-jones-rfd/func-help'
const increment = State.modify<number>((n) => n + 1)
const describeCount = State.gets<number, string>((n) => `count is ${n}`)
const program: State<number, string> = increment
.bind(() => increment)
.bind(() => describeCount)
program.run(0) // ['count is 2', 2]
program.eval(0) // 'count is 2'
program.exec(10) // 12State.of (Haskell's pure) lifts a value without touching the state, and toFunction() gives a (state) => [result, state] function that runs the computation.
Where a throw surfaces: a throw in a function you pass to map, bind, modify or gets is thrown from run(), eval() or exec(), not from the call that built the State.
Reader
Reader<R, A> is a computation that needs an environment R: configuration or services (a base URL, a logger, a client) supplied once, at run(env), instead of passed through every function. Reader.ask<Env>() reads the whole environment, Reader.asks(f) reads something derived from it, Reader.of(value) ignores it, and local(f) runs one reader in a modified environment. Nothing runs until run(env), and every run runs the chain again with the environment it is given, so the same program runs against a test environment and a real one.
import { Reader } from '@b-jones-rfd/func-help'
type Env = { baseUrl: string; log: (msg: string) => void }
const url = (path: string) => Reader.asks((env: Env) => `${env.baseUrl}${path}`)
const program = Reader.do(function* () {
const u = yield* url('/users')
const env = yield* Reader.ask<Env>()
env.log(`GET ${u}`)
return u
}) // Reader<Env, string>
program.run({ baseUrl: 'https://api.test', log: console.log })
// logs 'GET https://api.test/users', returns 'https://api.test/users'- A reader over part of the environment fits where the whole is supplied.
Readeris contravariant inR, so aReader<{ log: Logger }, void>can be used as aReader<Env, void>, in abindor adoblock. Reader.dotakes the most specific environment it yields. Naming the wholeEnvonce, for example withReader.ask<Env>(), types the block. A block that yields only readers over separate parts ({ log }and{ baseUrl }) needs the environment named:Reader.do<Env, A>(…).local(f)changes the environment for one reader only; a later step in the same chain sees the original. Nested calls apply the outerffirst.fmay also take a different outer environment, as Haskell'swithReaderdoes.
examples/reader.ts runs one program against two environments.
Where a throw surfaces: a throw in a function you pass to map, bind, asks or local, or in a Reader.do block, is thrown from run(), not from the call that built the Reader.
Do
Each type has a do that gives you Haskell's do notation through a generator function: write x <- m as const x = yield* m. Each yield* binds the value with its real type, with no annotation, and the block returns the concrete type, with no cast. A plain yield (without *) binds unknown, so use yield*.
import { Either, IO } from '@b-jones-rfd/func-help'
const sum = IO.do(function* () {
const a = yield* IO.of(1) // number
const b = yield* IO.from(() => 2) // number
return a + b
}) // IO<number>
sum.run() // 3
const half = (n: number): Either<string, number> =>
n % 2 === 0 ? Either.right(n / 2) : Either.left(`${n} is odd`)
const positive = (n: number): Either<RangeError, number> =>
n > 0 ? Either.right(n) : Either.left(new RangeError(`${n} is not positive`))
const checked = Either.do(function* () {
const a = yield* half(8) // 4
const b = yield* positive(a) // 4
return yield* half(b - 5) // Left('-1 is odd'): the block stops here
}) // Either<string | RangeError, number>
checked.getOrElse(() => 0) // 0Either.doandExcept.dorun the block at once, and the firstLeftor failure stops it.Either.do's Left type is the union of the Left types of everyEitherthe block yields.IO.do,AsyncIO.do,State.doandReader.dobuild a value that runs nothing until it is run, and each run starts the block afresh.AsyncIO.dotakes a plain generator function, not anasyncone: eachyield*waits for the step to resolve.State.doinfers the state type from the States the block yields.yield*works because every instance has a[Symbol.iterator]method that yields the instance once. It is there foryield*; spreading one gives a one-element array holding the instance.
examples/do.ts is a runnable example.
Where a throw surfaces: a throw in the block propagates from the do call for Either and Except, is thrown from run() (or eval()/exec()) for IO, State and Reader, and rejects the promise run() returns for AsyncIO.
Do notation for your own monad
Do runs the same blocks for a monad of your own: anything with map and bind, the Monad<T> interface. Pass its of to Do.run(of, block), or to Do.with(of) to get a runner. Do cannot know which monad of builds, so the result is typed Monad<A>; cast it back to your type.
For typed bindings, give your class the same [Symbol.iterator] the package's types have. Without it, use a plain yield and annotate the binding, which is typed any.
import { Do } from '@b-jones-rfd/func-help'
class Box<T> {
readonly value: T
constructor(value: T) {
this.value = value
}
static of<T>(value: T): Box<T> {
return new Box(value)
}
map<U>(f: (t: T) => U): Box<U> {
return new Box(f(this.value))
}
bind<U>(f: (t: T) => Box<U>): Box<U> {
return f(this.value)
}
// Lets `yield*` bind a Box with its value's type.
*[Symbol.iterator](): Generator<this, T, unknown> {
return (yield this) as T
}
}
const product = Do.run(Box.of, function* () {
const a = yield* Box.of(2) // number
const b = yield* Box.of(3) // number
return a * b
}) as Box<number>
product.value // 6Where a throw surfaces: a throw in the block surfaces the way your monad surfaces a throw in bind.
API
Full generated reference: b-jones-rfd.github.io/func-help.
Everything is exported from the root entry. The modules are small, and sideEffects: false lets bundlers drop the ones you don't import.
Either
| Export | Kind | Summary |
| --------------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Either | class | A Left<L> (usually an error) or a Right<R> (a success). Haskell's Either l r. |
| Either.left | static method | Construct a Left. Haskell's Left. |
| Either.right | static method | Construct a Right. Haskell's Right. |
| Either.of | static method | Lift a value into a Right. Haskell's pure. |
| Either.fromNullable | static method | null or undefined becomes a Left from onNull(); anything else is a Right. |
| Either.tryCatch | static method | Run effect: its result is a Right, a throw is a Left (unknown, or mapped by onError). |
| Either.do | static method | A do block over Either: yield* binds each Right, and the first Left stops it. The Left is the union of the yielded Lefts. Haskell's do. |
| Either.traverse | static method | Apply f to each item and collect the Rights; the first Left stops it. Haskell's traverse. |
| Either.sequence | static method | An array (or tuple) of Eithers as an Either of an array (or tuple); the first Left wins. Haskell's sequence. |
| isLeft | instance method | Type guard: narrows to the Left side. |
| isRight | instance method | Type guard: narrows to the Right side. |
| map | instance method | Apply f to a Right; a Left passes through. Haskell's fmap. |
| bind | instance method | Chain a step that returns an Either; a Left short-circuits. Haskell's >>=. |
| fold | instance method | Collapse to one value with onLeft or onRight. Haskell's either. |
| match | instance method | Collapse to one value with handlers { left, right }. |
| getOrElse | instance method | The Right value, or fallback(left). Haskell's fromRight, with a function. |
| swap | instance method | Exchange Left and Right. |
| tap | instance method | Run a side effect with a Right, keeping the Either. |
| mapLeft | instance method | Apply f to a Left; a Right passes through. Haskell's first (Data.Bifunctor). |
| bimap | instance method | Apply onLeft to a Left or onRight to a Right. Haskell's bimap. |
| catchError | instance method | Recover from a Left with a handler that returns an Either of the same Right type. Haskell's catchError. |
| [Symbol.iterator] | instance method | Lets yield* bind it in a do block. Not meant for spreading: [...x] is [x]. |
Except
| Export | Kind | Summary |
| --------------------- | --------------- | -------------------------------------------------------------------------------------------------------- |
| Except | class | A failure holding an Error, or a success holding an A. Like mtl's Except, with Error fixed. |
| Except.failed | static method | Construct a failure. Haskell's throwError. |
| Except.ok | static method | Construct a success. |
| Except.of | static method | Lift a value into a success. Haskell's pure. |
| Except.fromNullable | static method | null or undefined becomes a failure from onNull(); anything else is a success. |
| Except.tryCatch | static method | Run effect: its result is a success, a throw is a failure (non-Error throws are wrapped). |
| Except.fromEither | static method | An Either<Error, A> as an Except. Haskell's except. |
| Except.do | static method | A do block over Except: yield* binds each success, and the first failure stops it. Haskell's do. |
| Except.traverse | static method | Apply f to each item and collect the values; the first failure stops it. Haskell's traverse. |
| Except.sequence | static method | An array (or tuple) of Excepts as an Except of an array (or tuple). Haskell's sequence. |
| isError | instance method | true for a failure. |
| isOk | instance method | true for a success. |
| map | instance method | Apply f to a success; a failure passes through. Haskell's fmap. |
| bind | instance method | Chain a step that returns an Except; a failure short-circuits. Haskell's >>=. |
| fold | instance method | Collapse to one value with onError or onSuccess. |
| match | instance method | Collapse to one value with handlers { failed, ok }. |
| getOrElse | instance method | The success value, or fallback(error). |
| tap | instance method | Run a side effect with a success, keeping the Except. |
| mapError | instance method | Apply f (Error to Error) to a failure; a success passes through. Haskell's withExcept. |
| catchError | instance method | Recover from a failure with a handler that returns an Except of the same type. Haskell's catchError. |
| toEither | instance method | This Except as an Either<Error, A>. Haskell's runExcept. |
| [Symbol.iterator] | instance method | Lets yield* bind it in a do block. Not meant for spreading: [...x] is [x]. |
IO
| Export | Kind | Summary |
| ------------------- | --------------- | ------------------------------------------------------------------------------------------------------ |
| IO | class | A synchronous side effect, run only by run(). Haskell's IO a. |
| IO.of | static method | Lift a value into IO. Haskell's pure. |
| IO.from | static method | Wrap a side effect without running it. |
| IO.do | static method | A do block as an IO: yield* binds each result. Runs only on run(). Haskell's do. |
| IO.traverse | static method | An IO that applies f to each item and runs the results in order. Haskell's traverse. |
| IO.sequence | static method | An IO that runs an array (or tuple) of IOs in order. Haskell's sequence. |
| run | instance method | Run the effect and return its result. Runs the whole chain on every call. |
| map | instance method | Transform the result. Haskell's fmap. |
| bind | instance method | Chain a step that returns an IO. Haskell's >>=. |
| tap | instance method | Run an extra side effect with the result, keeping the result. |
| attempt | instance method | An IO<Except<A>>: a throw in the chain becomes a failure, and run() never throws. Haskell's try. |
| [Symbol.iterator] | instance method | Lets yield* bind it in a do block. Not meant for spreading: [...x] is [x]. |
AsyncIO
| Export | Kind | Summary |
| ------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| AsyncIO | class | An asynchronous side effect, run only by run(). |
| AsyncIO.of | static method | Lift a value into AsyncIO. Haskell's pure. |
| AsyncIO.from | static method | Wrap a promise-returning effect without running it. |
| AsyncIO.fromIO | static method | Lift an IO; it runs each time the AsyncIO runs. Haskell's liftIO. |
| AsyncIO.fromExcept | static method | Lift an Except; a failure rejects with its Error. Haskell's liftEither. |
| AsyncIO.do | static method | A do block as an AsyncIO: yield* waits for and binds each result. Haskell's do. |
| AsyncIO.traverse | static method | Apply f to each item and run the results one after another. Haskell's traverse. |
| AsyncIO.sequence | static method | Run an array (or tuple) of AsyncIOs one after another. Haskell's sequence. |
| AsyncIO.mapConcurrently | static method | Apply f to each item and run the results at the same time, in input order. Haskell's mapConcurrently (async). |
| AsyncIO.concurrently | static method | Run an array (or tuple) of AsyncIOs at the same time; a typed Promise.all. Haskell's concurrently (async), for any number. |
| run | instance method | Run the effect and return a promise of its result. Never throws; every error rejects. |
| map | instance method | Transform the result once it resolves. Haskell's fmap. |
| bind | instance method | Chain a step that returns an AsyncIO. Haskell's >>=. |
| tap | instance method | Run an extra side effect with the result, keeping the result. |
| attempt | instance method | An AsyncIO<Except<A>>: a rejection in the chain becomes a failure, and run() never rejects. Haskell's try. |
| [Symbol.iterator] | instance method | Lets yield* bind it in a do block. Not meant for spreading: [...x] is [x]. |
State
| Export | Kind | Summary |
| ------------------- | --------------- | ------------------------------------------------------------------------------------------ |
| State | class | A computation over a state S that produces an A. Haskell's State s a. |
| State.of | static method | Lift a value, leaving the state unchanged. Haskell's pure. |
| State.get | static method | Produce the current state. |
| State.put | static method | Replace the state. |
| State.modify | static method | Transform the state with f. |
| State.gets | static method | Produce a value projected from the state with f. |
| State.do | static method | A do block as a State: yield* binds each value, threading the state. Haskell's do. |
| map | instance method | Transform the result. Haskell's fmap. |
| bind | instance method | Chain a step that returns a State. Haskell's >>=. |
| run | instance method | Run from initial, returning [result, finalState]. Haskell's runState. |
| eval | instance method | Run from initial, returning the result only. Haskell's evalState. |
| exec | instance method | Run from initial, returning the final state only. Haskell's execState. |
| toFunction | instance method | A (state) => [result, state] function that runs the computation. |
| [Symbol.iterator] | instance method | Lets yield* bind it in a do block. Not meant for spreading: [...x] is [x]. |
Reader
| Export | Kind | Summary |
| ------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------ |
| Reader | class | A computation that reads an environment R, supplied at run(env); contravariant in R. Haskell's Reader r a. |
| Reader.of | static method | Lift a value, ignoring the environment. Haskell's pure. |
| Reader.ask | static method | Read the whole environment. Haskell's ask. |
| Reader.asks | static method | Read a value derived from the environment with f. Haskell's asks. |
| Reader.do | static method | A do block as a Reader; the environment is the most specific one yielded. Haskell's do. |
| map | instance method | Transform the result. Haskell's fmap. |
| bind | instance method | Chain a step that returns a Reader; it gets the same environment. Haskell's >>=. |
| local | instance method | Run this reader with f(env); later steps see the original. Haskell's local (and withReader), as a method. |
| run | instance method | Run with an environment and return the result. Haskell's runReader. |
| [Symbol.iterator] | instance method | Lets yield* bind it in a do block. Not meant for spreading: [...x] is [x]. |
Do
| Export | Kind | Summary |
| --------- | ------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Do | class | do notation for a monad of your own, given by its of. The package's types have their own do. |
| Do.run | static method | Run one block over of; yield* on an iterable monad gives typed bindings. The result is Monad<A>; the caller casts it. |
| Do.with | static method | Fix of, returning a runner that takes the block. The result is Monad<A>, as Do.run. |
Types
| Export | Kind | Summary |
| ----------------- | --------- | -------------------------------------------------------------------------- |
| Monad<T> | interface | Anything with map and bind; what Do builds on. |
| Effect<A> | type | A synchronous effect: () => A. |
| AsyncEffect<A> | type | An asynchronous effect: () => Promise<A>. |
| StatePair<S, A> | type | The pair a state computation produces: [result, state], result first. |
| Unit | type | void: the result of an effect run only for what it does. Haskell's (). |
Changes in 0.7
0.7.0 removes two exports so that 1.0 doesn't promise them.
IO.fromPromiseis removed. UseAsyncIO.from(thunk)for async work, orIO.from(thunk)if you really want anIO<Promise<A>>.StateTis removed. Copysrc/monads/StateT.tsfrom 0.6.x into your app, changing its../types.jsand../utils/Do.jsimports to@b-jones-rfd/func-help, or useStatefor the pure part and the wrapped monad for the effect. A typedStateTis planned after 1.0.
Contributing
This is a personal project maintained for my own work and is not accepting contributions. Bug reports via issues are welcome; security problems go through private reporting.
If you want to build it locally:
pnpm install
pnpm dev # vitest in watch mode
pnpm run ci # lint, test (including type tests), build, package checks
pnpm run docs # generate the API reference into docs/The tests also run in Chromium and WebKit. Install those browsers once with
pnpm exec playwright install chromium webkit, then run
pnpm run test:browser.
Versioning
SemVer. A change to an exported type is treated as an API change. See the CHANGELOG for release notes and breaking changes.
License
MIT.
