Andrii Melnikov
Whoever thinks that the products of programmers are the programs they write is deeply mistaken. A programmer must produce trustworthy solutions and present them in the form of convincing arguments; the text of the program is merely accompanying material to which those arguments apply.
— Edsger W. Dijkstra (paraphrased)
function sum(a, b) {
return parseInt(a, 10) + parseInt(b, 10)
}Everything flows, everything changes
— Heraclitus
The whole is greater than the sum of its parts
— Aristotle
function sum(a, b) {
- return parseInt(a, 10) + parseInt(b, 10)
+ return summator(prepareArgs(a, b))
}
Change and impermanence are built into the very reason code exists.
A flower needs time to grow. So there's no need to strain — better to observe.
— Yongey Mingyur Rinpoche
VCS?
function sum(a, b) {
- return parseInt(a, 10) + parseInt(b, 10)
+ return summator(prepareArgs(a, b))
}
A bit of fun linguistics: change comes from the same root as exchange.
Behaviour:
sum(2, 2) returns 4)sum(2, 2) returns something that isn't a number)Its proofs:
!exists(!safe) ≡ all(liveness) ⇒ all(safe) ≡ all(liveness)describe('sum', () => {
it('2 + 2 = 4', () => expect(sum(2, 2)).toBe(4))
})
How many tests are enough?
Program testing can be used to show the presence of bugs, but never to show their absence!
— Edsger W. Dijkstra
f(x) = yf(2) = 1The set of points a program is defined on is usually close to infinite.
a + b >= a && a + b >= bsort(sort(x)) ≡ sort(x)reverse is its own inverse: reverse(reverse(str)) ≡ strlength(sort(x)) ≡ length(x)typeof sum(a, b) ≡ 'number'Prove the property statically with Coq / Agda / TLA+ / Lean

Just check the property on very many random points
∀ x ∈ random() × 1000
Steps:
Libraries:
function convertFrom(structFromBackend) {
...
return structForFrontend;
}
function convertTo(structForFrontend) {
...
return structFromBackend;
}function isRevertable(structFromBackend) {
var structForFrontend = convertFrom(structFromBackend);
var structForBackend = convertTo(structForFrontend);
expect(structFromBackend).toEqual(structForBackend);
}jsc.string // generates strings
jsc.record({ ... }) // generates records
jsc.elements([ ... ]) // picks one of the elements
jsc.oneof([ ... ]) // uses one of the generatorsimport * as jsc from 'jsverify'
var familyInfoGen = jsc.record({
type: jsc.elements(['espoused', 'single', 'common_law_marriage', undefined]),
members: jsc.array(
jsc.record({
role: jsc.elements(['sibling', 'child', 'parent', 'spouse']),
fio: jsc.record({
firstname: jsc.oneof([jsc.string, jsc.undefined]),
lastname: jsc.oneof([jsc.string, jsc.undefined]),
middlename: jsc.oneof([jsc.string, jsc.undefined])
}),
dependant: jsc.oneof([jsc.boolean, jsc.undefined])
})
)
});type === 'espoused'type !== 'espoused', there must be nonesmap maps the elements of the generated sequence through a function:
var familyInfoGenFixed = familyInfoGen
.smap(dropManySpouseOrFixMaritalStatus, identity);● convertFrom and convertTo properties
› convertFrom -> convertTo save original shape (
{"type":"single","members":[{"role": "sibling", "fio": {}}]}
)
Difference:
- Expected
+ Received
Object {
"type":"single"
"members": Array [
Object {
"role": "sibling",
"fio": Object {},
+ "dependant": false
}
]
}import { Record, Literal as L, Union, Array, Boolean, String, Void } from 'runtypes'
const FamilyStruct = Record({
type: Union(L('espoused'), L('single'), L('common_law_marriage'), Void),
members: Array(
Record({
role: Union(L('sibling'), L('child'), L('parent'), L('spouse')),
fio: Record({
firstname: String.Or(Void),
lastname: String.Or(Void),
middlename: String.Or(Void)
}),
dependant: Boolean.Or(Void)
})
)
})
const FamilyWithSingleSpouse = FamilyStruct.withConstraint(
isSingleSpouse,
{ tag: 'FamilyStructWithSingleSpouse' }
)
function isSameShape(structFromBackend) {
var structForFrontend = convertFrom(structFromBackend);
var structForBackend = convertTo(structForFrontend);
expect(FamilyWithSingleSpouse.guard(structForBackend)).toBe(true);
}import { addTypeToRegistry, makeJsverifyArbitrary } from 'runtypes-generate';
addTypeToRegistry(
'FamilyStructWithSingleSpouse',
() => makeJsverifyArbitrary(FamilyWithSingleSpouse)
.smap(dropManySpouseOrFixMaritalStatus, x => x)
);
jsc.assert(
jsc.forall(makeJsverifyArbitrary(FamilyWithSingleSpouse), isSameShape)
)type Family = {
type: 'espoused' | 'single' | 'common_law_marriage' | undefined | null,
members: Array<{
role: 'sibling' | 'child' | 'parent' | 'spouse',
fio: {
firstname: string | undefined | null,
lastname: string | undefined | null,
middlename: string | undefined | null
},
dependant: boolean | undefined | null
}>
}
function convertFrom(structFromBackend: Family): ConvertedFamily {}
function convertTo(structForFrontend: ConvertedFamily): Family {}Type annotations aren't just part of a language — they're a separate language.
It can be Turing-complete:
With static typing we write code in two languages: one does something, and the other makes sure the first doesn't do anything extra.
Programming with computations at the level of the type system is called type-level programming.
interface Nat {
prev?: any
isZero: 'true' | 'false'
}
interface Positive {
prev: Positive | _0
isZero: 'false'
}
type Succ<N extends Positive | _0> = { prev: N; isZero: 'false' }
type _0 = { isZero: 'true' }
type _1 = Succ<_0>
type _2 = Succ<_1>
This trick is known as Church numerals (strictly speaking, Peano-style numbers).
// v1 :: Vector<_1, number>
const v1 = Vector.create([1])
// v2 :: Vector<_2, number>
const v2 = Vector.create([2, 3])
console.log(v2.zip(v1.append(v1))) // Vector([[2,1],[3,1]])
v2.zip(v1) // error
[ts]
Argument of type 'Vector<Succ<Succ<_0>>, number>' is not assignable to parameter of type 'Vector<Succ<Succ<Succ<_0>>>, number>'.
Type 'Succ<Succ<_0>>' is not assignable to type 'Succ<Succ<Succ<_0>>>'.
Types of property 'prev' are incompatible.
Type 'Succ<_0>' is not assignable to type 'Succ<Succ<_0>>'.
Types of property 'prev' are incompatible.
Type '_0' is not assignable to type 'Succ<_0>'.
Property 'prev' is missing in type '_0'.
Dependent types built into the compiler: Coq, Agda, Idris — types restricted down to values
function add<A extends Nat, B extends Nat>(
a: A, b: B
): Add<A, B>
THEOREM PROVING IN DA HOUSE!
Refinement (liquid) types built into the compiler:
type nat = { v: number | 0 ≤ v }
Outside research projects they don't really exist yet:
mean(list) = divide(sum(list), length(list)) — prove that it returns a number for any list of numbers.
Statically:
sum(list: number[]): number
length(list: number[]): number
div(a: number, b: number): number
mean(list: number[]): number
Proof by construction, a.k.a. verification (from verus — true).
The way the program is built guarantees a property.
Dynamically:
jsc.forall(
[jsc.array(jsc.number)],
list => isNumber(mean(list))
)
Proof by results, a.k.a. validation (from valere — to be worth).
The result of running the program has a property.
Static (by construction):
Dynamic (by results):
const FamilyStruct = Record({
type: Union(L('espoused'), L('single'),
L('common_law_marriage'), Void),
members: Array(
Record({
role: Union(L('sibling'), L('child'),
L('parent'), L('spouse')),
fio: Record({
firstname: String.Or(Void),
lastname: String.Or(Void),
middlename: String.Or(Void)
}),
dependant: Boolean.Or(Void)
})
)
})type Family = {
type: 'espoused' | 'single'
| 'common_law_marriage' | undefined | null,
members: Array<{
role: 'sibling' | 'child'
| 'parent' | 'spouse',
fio: {
firstname: string | undefined | null,
lastname: string | undefined | null,
middlename: string | undefined | null
},
dependant: boolean | undefined | null
}>
}import { Static } from 'runtypes'
type Family = Static<typeof FamilyStruct>
From a single description of the data (a spec) we get:
Dynamic vs static proof is now just a matter of tactics:
Static proof — is the code's internal structure stable and won't be rewritten soon?
Dynamic proof — will the code most likely be rewritten many times soon (prototype stage)?
Task: a new module that computes the mean of a list of numbers.
TypeScript, --allowJs
function meanFn(list) {
return divide(sum(list), length(list))
}The module is experimental; business changes and refactorings are likely. Stage: active development.
mean.js
import { Contract, Array, Number } from 'runtypes';
const meanConstraint = ([list], result) =>
result >= min(list) && result <= max(list)
export const MeanSpec = Contract(Array(Number), Number)
.withConstraint(meanConstraint);
export const mean = MeanSpec.enforce(meanFn)mean.test.js
import { makeJsverifyArbitrary } from 'runtypes-generate';
import { MeanSpec, mean } from './mean';
jsc.assert(jsc.forall(
[makeJsverifyArbitrary(MeanSpec.reflect.argsTypes)],
list => mean(list)
))The module's internal structure has stabilised. Stage: maintenance.
mean.js → mean.ts
function sum(list: number[]): number
function length(list: number[]): number
function div(a: number, b: number): number
If requirements change drastically — say, we need the median instead of the mean:
mean.ts → mean.js and back to step 1, practically without losses.
What else useful can we come up with?
mean.js
export const mean = trace('module/mean', meanFn)
When the application exits, or on a special signal:
import { mean } from './mean.js'
import convert from 'call-to-jasmine-test'
mean.calls // array of calls made while the app was running
convert(mean.calls) // code of jasmine test cases
/*
it(1, () => expect(mean([1, 2, 3])).toEqual(2))
...
*/import { mean } from './mean.js';
import infer from 'runtypes-infer'
mean.calls // array of calls made while the app was running
infer(mean.calls) // type description for runtypes
/*
Contract(Array(Number), Number)
*/
Automatic annotations — only for Clojure :(

function mean(list) {
return divide(sum(list), length(list))
}
[[1, 2, 3], 2], ...
describe(() => it(() => expect(mean([1, 2, 3])).toEqual(2)))const MeanSpec = Contract(Array(Number), Number)
jsc.assert(jsc.forall(
[makeJsverifyArbitrary(MeanSpec.reflect.argsTypes)],
list => mean(list)
))
mean.js → mean.tsHow do you prove a change is backwards compatible?
mean.ts
We had tests:
it(() => expect(mean([1, 2, 3])).toBe(2))
it(() => expect(mean([])).toBe(0))
And types:
function mean(list: number[]): numberBut this change goes unnoticed:
function mean(list) {
- return meanFn(list)
+ return medianFn(list)
}const MeanSpec = Contract(Array(Number), Number)import { mean as prevMean, MeanSpec as prevSpec } from 'project-prev/mean';
import { mean as currMean, MeanSpec as currSpec } from 'project-curr/mean';
// the specs themselves haven't changed (the "static" approach)
assert(isEqualSpec(prevSpec, currSpec))
jsc.assert(
jsc.forall(
[makeJsverifyArbitrary(prevSpec.reflect.argsTypes)],
// and neither have the results (the "dynamic" approach)
list => prevMean(list) === currMean(list)
)
)
Dynamic:
Number.withConstraint(v => v >= 0)
How do you generate data of such a type?
User page · in list To Do: Frontend
Build the user page. API request GET /userInfo:
{ fio: { lastname: 'Ivanov', firstname: 'Ivan' }, balance: 1000000 }
Displayed result: Name: Ivan Ivanov · Balance: 1 000 000 ₽
If the API returns invalid data, show a placeholder: An unexpected error occurred
Now let's try the top-down approach.
The overall spec:
type App = {
{
fio: {
firstname?: string,
lastname?: string
} | !isEmpty v.lastname || !isEmpty v.firstname,
balance: PositiveNumber
}: {
fio: FioString,
amount: AmountString
};
any: HtmlError
}Cases:
expect(app({
fio: { lastname: 'Ivanov', firstname: 'Ivan' },
balance: 1000000
})).toEqual({
fio: 'Ivan Ivanov',
amount: '1000000 ₽'
})
...const solve = require('rambo').solve
const solution = solve([1, 2, 3, 4], [5, 6, 7, 8])
console.log(solution.name) // "R.map(R.add(4))"{ firstname?: string, lastname?: string }
| !isEmpty v.lastname || !isEmpty v.firstname
-> FioString
PositiveNumber -> AmountString
...
formatFio(
{ firstname?: string, lastname?: string }
): FioString
formatAmountRub(x: number): AmountStringA well-posed question is half the answer
runtypes-generate, io-ts-generatefunction genPosNumber() {
return Math.random() * 10000000000;
}function forall(argGenerators, propertyFn) {
return function() {
var generatedArgs = argGenerators.map(gen => gen());
return {
success: propertyFn(...generatedArgs),
args: generatedArgs
};
}
}function assert(property, tries = 100) {
for (var i = 0; i < tries; i++) {
var res = property();
if (!res.success) {
throw new Error(
'Property hasnt held on arguments: '
+ JSON.stringify(res.args, null, 2)
);
}
}
}it('forall a, b - a + b >= a && a + b >= b', () => {
assert(forall(
[genPosNumber, genPosNumber],
function (a, b) {
return a + b >= a && a + b >= b;
}
))
})var a = { a: 1 };
changeObj(a) // hidden change
var a = { a: 1 };
var changedA = changeObj(a) // observable change
FRP:
var getCurrentUnixTimeWithDelay = () => Time.now() + 5
getCurrentUnixTimeWithDelay()
...
// hidden change
getCurrentUnixTimeWithDelay()
var time = Time.toBehavior()
var withDelay = time.map(now => now + 5)
// observable change
withDelay.sample(Time.interval(1)).subscribe(x => console.log(x))
Dynamic: Min(Number, 0)
Static: Min<Number, _0>
