This commit is contained in:
Rowan 2025-04-07 03:03:40 -05:00
parent 50f3cff3d9
commit 55be1efee1
2 changed files with 75 additions and 1 deletions

53
src/algebra/io.js Normal file
View file

@ -0,0 +1,53 @@
import { Algebra, Monad } from './index.js'
/** @import { Fn, InferredMorphism, Morphism } from './types.js' */
/** @template {Fn} T */
export class IO extends Algebra(Monad) {
_effect
/**
* @type {T} effect
*/
constructor(effect) {
super()
this._effect = effect
}
/**
* @template {Fn} T
* @param {T} a
*/
static of(a) {
return new IO(() => a)
}
/**
* @param {InferredMorphism<T>} f
*/
chain(f) {
return IO.of(() => f(this.run()).run())
}
/**
* @param {InferredMorphism<T>} f
*/
map(f) {
return IO.of(() => f(this.run()))
}
/**
* @template {Fn} U
* @this {IO<T>}
* @param {IO<Morphism<T, U>>} other
* @returns {IO<U>}
*/
ap(other) {
return IO.of(() => other.run()(this.run()))
}
run() {
return this._effect()
}
}

View file

@ -1,7 +1,7 @@
import { Pure, Suspend } from './free.js' import { Pure, Suspend } from './free.js'
import { AlgebraWithBase, Category, Comonad, Foldable, Monoid } from './index.js' import { AlgebraWithBase, Category, Comonad, Foldable, Monoid } from './index.js'
/** @import { InferredMorphism } from './types.js' */ /** @import { InferredMorphism, Morphism } from './types.js' */
const Nil = Symbol('Nil') const Nil = Symbol('Nil')
@ -26,6 +26,27 @@ class ListPure extends AlgebraWithBase(Pure)(Category, Foldable, Monoid) {
return Empty return Empty
} }
/**
* @template U
* @this {ListPure<T>}
* @param {Morphism<T, ListPure<U>>} f
* @returns {ListPure<U>}
*/
chain(f) {
return f(this.head())
}
/**
* @template U
* @this {ListPure<T>}
* @param {Morphism<T, U>} f
* @returns {ListPure<U>}
*/
map(f) {
return new ListPure(f(this._value))
}
/** /**
* @template U * @template U
* @param {(acc: U, value: T) => U} f * @param {(acc: U, value: T) => U} f