Skip to content

Instantly share code, notes, and snippets.

@mlhaufe mlhaufe/OAlgPeano.ts
Created Jan 27, 2018

Embed
What would you like to do?
ObjectAlgebra Peano Numbers
interface PeanoAlg<T> {
Zero(): T
Succ(pred: T): T
}
type PeanoData = { kind: "Zero" } | { kind: "Succ", pred: PeanoData }
let peanoFactory: PeanoAlg<PeanoData> = {
Zero(): PeanoData { return { kind: "Zero" } },
Succ(pred: PeanoData): PeanoData { return { kind: "Succ", pred} }
}
interface IPeanoAdd {
add(peanoData: PeanoData): PeanoData
}
let peanoAdd: PeanoAlg<IPeanoAdd> = {
Zero(): IPeanoAdd { return {
add(peanoData) { return peanoData }
}},
Succ(pred: IPeanoAdd): IPeanoAdd { return {
add(peanoData) {
return peanoFactory.Succ(pred.add(peanoData))
}
}}
}
interface IPeanoMul extends IPeanoAdd {
mul(peanoData: PeanoData): PeanoData
}
let peanoMul: PeanoAlg<IPeanoMul> = {
Zero(): IPeanoMul { return {
add: peanoAdd.Zero().add,
mul(peanoData) { return peanoFactory.Zero() }
}},
Succ(pred: IPeanoMul) { return {
add: peanoAdd.Succ(pred).add,
mul(peanoData) {
return pred.add(pred.mul(peanoData))
}
}}
}
interface IToString {
toString(): string
}
let peanoToString: PeanoAlg<IToString> = {
Zero(): IToString { return {
toString(){ return "Z" }
}},
Succ(pred: IToString): IToString { return {
toString(){ return `S(${pred})`}
}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.