Moore

class Moore<I, O>(val output: O, val step: (I) -> Moore<I, O>) : K3<Moore.T, Unit, I, O> (source)

A Moore machine: a current output together with a step function that consumes an input and yields the next machine.

Useful as a resumable left fold whose intermediate result is always observable. Encoded as K3 with a phantom Unit so that it fits Profunctor<T, F>.

Instances: MooreFunctor, MooreApplicative, MooreCopointed, MooreComonad, MooreProfunctor.

val sum = Moore.unfold(0, { s -> s }) { s, i: Int -> s + i }
sum.run(listOf(1, 2, 3)) // 6
sum.scan(listOf(1, 2, 3)) // [0, 1, 3, 6]
(sum lmap String::length).run(listOf("ab", "c")) // 3

Constructors

Link copied to clipboard
constructor(output: O, step: (I) -> Moore<I, O>)

Types

Link copied to clipboard
object Companion
Link copied to clipboard
class T

Properties

Link copied to clipboard
val output: O

the output of the current state.

Link copied to clipboard
val step: (I) -> Moore<I, O>

the transition to the next machine.

Functions

Link copied to clipboard
infix fun <B> ap(f: Moore<I, (O) -> B>): Moore<I, B>

Runs f and this machine in lockstep, applying the functions to the outputs.

Link copied to clipboard
fun <J, B> dimap(f: (J) -> I, g: (O) -> B): Moore<J, B>

Pre-composes f on the inputs and post-composes g on the outputs.

Link copied to clipboard
fun duplicate(): Moore<I, Moore<I, O>>

Returns a machine whose outputs are the machines reachable from this one.

Link copied to clipboard
infix fun <B> extend(f: (Moore<I, O>) -> B): Moore<I, B>

Applies f to every machine reachable from this one.

Link copied to clipboard
fun extract(): O

Returns the current output.

Link copied to clipboard
fun feedAll(inputs: Iterable<I>): Moore<I, O>

Feeds every input to the machine and returns the resulting machine.

Link copied to clipboard
infix fun <B> fmap(f: (O) -> B): Moore<I, B>

Maps every output of the machine.

Link copied to clipboard
infix fun <J> lmap(f: (J) -> I): Moore<J, O>

Pre-composes f on the inputs.

Link copied to clipboard
infix fun <B> rmap(g: (O) -> B): Moore<I, B>

Post-composes g on the outputs.

Link copied to clipboard
fun run(inputs: Iterable<I>): O

Feeds every input to the machine and returns the final output.

Link copied to clipboard
fun scan(inputs: Iterable<I>): List<O>

Returns every output observed while feeding the inputs, starting with the current one.