Andrii Melnikov
var URL = 'https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cats';
function app() {
document.querySelector('button').addEventListener(
'click',
() => fetch(URL)
.then(response => response.json())
.then(json => json.data.image_url)
.then(gifSrc => document.querySelector('img').setAttribute('src', gifSrc))
);
}
document, setAttributefetchfunction calcAnything(value) {
var a = calcA(value);
var b = calcB(value);
return calcC(value, b);
}
vs
function doSomething(value) {
var a = doSomethingA(value);
var b = doSomethingB(value);
return doSomethingC(value, b);
}?
function calcAnything(value) {
var a = calcA(value);
var b = calcB(value);
return calcC(value, b);
}
vs
function doSomething(value) {
var a = doSomethingA(value);
var b = doSomethingB(value);
return doSomethingC(value, b);
}function calcAnything(value) {
return calcC(value, calcB(value));
}?

function calcLengthAndSum() { ... }
function calcLength(list) {
return calcLengthAndSum(list).length;
}
function calcMean(list) {
var res = calcLengthAndSum(list);
return res.sum / res.length;
}
vs
function sendRequestAndWriteFile() { ... }
function sendRequest() {
return sendRequestAndWriteFile({ onlyRequest: true });
}
function sendRequestAndWriteFileOnUrl(url) {
return sendRequestAndWriteFile({ url: url });
}doSomething({
sendMetrics: true,
urlSomeAction: '/action',
logToFile: './log',
progressBar: false,
afterAction: () => ...,
beforeAction: () => ...
})it('2 + 2 = 4', () => {
var result = add(2, 2);
expect(result).toBe(4);
})it('remoteAdd send args to endpoint', () => {
var postCalls = [];
var fakeRes = {};
mock(HttpClient, { post: (...args) => {
postCalls.push(args);
return fakeRes;
}})
var result = remoteAdd(2, 2);
expect(postCalls.length).toBe(1);
expect(postCalls[0]).toEqual({url: URL, params: {a: 2, b: 2}});
expect(result).toBe(fakeRes);
}); function add(a, b) {
- return a + b;
+ return {result: a + b};
}
Test failed: expected 4, received {result: 4}
function remoteAdd(a, b) {
+ document.dispatchEvent(new LogEvent([a, b]));
return HttpClient.post({url: URL, params: {a, b}});
}
Test passed

-function remoteAdd(a, b) {
+function remoteAdd(document, HttpClient, a, b) {
document.dispatchEvent(new LogEvent([a, b]));
return HttpClient.post({ url: URL, params: {a, b} });
}

function remoteAdd(HttpClient, a, b) {
+ HttpClient.options({url: URL, params: {a, b}})
return HttpClient.post({ url: URL, params: {a, b} });
}Bad:
var result = remoteAdd(HttpClient, a, b)
expect(result).toEqual(output)
expect(HttpClient.post.mock.calls)
.toEqual(postCalls)Good:
var world = new World()
var result = remoteAdd(world, a, b)
expect(result).toEqual(output)
expect(world.changes()).toEqual(sideEffects)Everything changes and nothing stands still
— Heraclitus
add(2, 2);
vs
try {
remoteAdd(2, 2);
} catch (e) {
handleError(e);
}calc(a, b) === calc(a, b)
vs
var res1 = fetchSomething(a);
// data on the server changed
var res2 = fetchSomething(a);
res1 !== res2
function parse(str: string): number | null {
return isLikeNumber(str) ? parseInt(str) : null;
}
function add(a: number, b: number) {
return a + b;
}
add(parse('aaa'), 3) // compile-time error
But types don't help with effectful code:
function patchDOM(patch: DOMPatch): void { ... }
function serverProgram() {
...
patchDOM(patch); // run-time error
}type DB = { type: 'DB' };
type User = { username: string, uid: number };
function createUser(username: string): Eff<{ write: DB }, User> { ... }
function lookupUser(username: string): Eff<{ read: DB }, ?User> { ... }Tools:
Interactive development — Nikita Prokopov

> deleteUser(12)
{result: "OK"}
> deleteUser(12)
{error: "User not found"}
> addUser(12, data)
> deleteUser(12)
{result: "OK"}Possible solutions:
Side-effect-free functions have properties — like math functions:
var sortIdempotent =
jsc.forall("string -> nat", "array string", function (f, arr) {
return _.isEqual(_.sortBy(_.sortBy(arr, f), f), _.sortBy(arr, f));
});
jsc.assert(sortIdempotent);
Tools: testcheck, jsverify

printSum(list: Array): PrintedSumToScreenEffect
sum(list: Array): number
printToScreen(value: number): PrintedSumToScreenEffectTools:
People draw UML diagrams to understand the overall structure of a program. That's exactly what Haskell programmers do when they come up with type signatures.
— Simon Peyton Jones
sum(1, 2, 3, 4)
// -> 10
print('Hello', screen)
// -> prints 'Hello' to screen
function printSum(list) {
print(sum(...list), screen)
}Tools:
More consistent and correct, but slower and less agile.
Main tool: strong static types
More agile and fast, but less consistent.
Main tool: REPL

function calcForItem(...) {
...
var cachedResult = localStorage
.getItem(argsHash);
if (cachedResult) {
return cachedResult;
} else {
...
localStorage.setItem(argsHash, res)
return res;
}
}
“Have you read Cat's Cradle?”
“No.”
“In that novel the world ends because of a molecule that turns any water it touches into ice. All the waters of the world are connected — pond, stream, river, lake, ocean — so the whole world freezes. The molecule is called ice-nine.”
Implicit execution:
> var user = requestUser();
{ fio: "Ivan Ivanov", age: 19 }
> var res = writeToFile(user.fio);
{ success: true }Explicit execution:
> var req = requestUser();
{ type: "http", url: "/user", payload: {id: 2} }
> var user = runEffect(req);
{ fio: "Ivan Ivanov", age: 19 }
> var writing = writeToFile(user.fio);
{ type: "file", name: "./sys.log", data: "Ivan Ivanov" }
> var res = runEffect(writing)
{ success: true }Pure:
var res1 = doSmth1(start);
var res2 = doSmth2(res1);
var res3 = doSmth3(res2);
With effects:
var eff1 = doSmth1(start);
var res1 = runEffect(eff1);
var eff2 = doSmth2(res1);
var res2 = runEffect(eff2);
var eff3 = doSmth3(res2);
var res3 = runEffect(eff3);
Sync:
var res1 = doSmth1(start);
var res2 = doSmth2(res1);
var res3 = doSmth3(res2);
Async:
doSmth1(res1 => {
doSmth2(res1, res2 => {
doSmth3(res2);
});
});
Without errors:
var res1 = doSmth1(start);
var res2 = doSmth2(res1);
var res3 = doSmth3(res2);
With error handling:
var res1 = doSmth1(start);
if (!isError(res1)) {
var res2 = doSmth2(res1);
if (!isError(res2)) {
var res3 = doSmth3(res2);
} else { handle(res2) }
} else { handle(res1) }
Non-nullable:
var res1 = doSmth1(start);
var res2 = doSmth2(res1);
var res3 = doSmth3(res2);
With null checks:
var res1 = doSmth1(start);
if (!isNull(res1)) {
var res2 = doSmth2(res1);
if (!isNull(res2)) {
var res3 = doSmth3(res2);
}
}
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated.
— Wikipedia
Control-flow primitives:
ifswitch … casewhile, for{ some code }break, continuethrow new Error()return res, yield res

Today:
var res1 = doSmth1(start);
if (!isError(res1)) {
var res2 = doSmth2(res1);
if (!isError(res2)) {
var res3 = doSmth3(res2);
} else { handle(res2) }
} else { handle(res1) }With GOTO:
error:
handle(errorMsg)
global errorMsg;
function exitIfErr(res) {
if (isError(res)) {
errorMsg = res;
goto error;
} else {
return res;
}
}
// calculation
var res1 = exitIfErr(doSmth1(start));
var res2 = exitIfErr(doSmth2(res1));
var res3 = exitIfErr(doSmth3(res2));The mother of all statements: if value then goto label
i = 1;
while (i < 4) {
print(i);
i = i + 1;
}i = 1
START: if i = 4 then goto END
print(i)
i = i + 1
goto START
END:
Calculation:
c = add(inc(a), dec(b))
Order of execution:
inc(a), dec(b)add(inc(a), dec(b))Conditional jump:
if add(a, b) then goto LABEL
Order of execution:
add(a, b)if (add(a, b))goto LABELImagine a calculation evaluated in reverse order: c = add(inc(a), dec(b))
add(placeholder1, placeholder2)inc(a)dec(b)if(a, goto label)
if(placeholder1, placeholder2)agoto labelvar x = {}
x && x.obj && x.obj.prop
var x = {}
and(and(x, x.obj), x.obj.prop)
Normal order a.k.a. call-by-name (call-by-need) a.k.a. lazy evaluation. Our languages aren't Turing-complete without it.
Theorem: every computation can be carried out in normal order.
The first "programming languages", 1936:
The first computers, 1944: von Neumann architecture (inspired by the Turing machine)
With applicative order: everything is calculation + control flow
With normal order: everything is calculation
Continuation-passing style:
Async:
requestUser(user => {
writeToFile(user.fio,
res => { ... }
)
})Errors:
doWithErrors(res => {
doWithErrors2(
res,
res2 => { ... },
handleErr
)
}, handleErr)var a = 1 + 2;
var b = a + 4 // 7
var firstCalc = cont => cont(1 + 2)
var b = firstCalc(a => a + 4) // 7
cont === a => a + 4var r
var a = callcc(cont => {
r = cont;
cont(1 + 2) // 7
return 1 + 2
});
var b = a + 4 // 7
r(1 + 2) // 7var cont;
function throw(err) {
cont(err);
}
function try(program, handleErr) {
var res = callcc(c => {
cont = c;
program()
})
if (isError(res)) {
handleErr(res)
}
}
try(
() => {
var a = doWithErrors() // throw new Error()
...
},
err => { ... }
)
var cont, currCont
function perform(effect) {
return callcc(c => {
currCont = c;
return cont(effect);
})
}
function run(program, handleEffect) {
var res = callcc(c => {
cont = c;
program()
})
if (isEffect(res)) {
currCont(handleEffect(res))
}
return res;
}run(
() => {
var user = perform(requestUser())
var fio = user.fio
var res = perform(writeToFile(fio))
},
eff => runEffect(eff)
)
writeToFile(requestUser().fio)
// vs
pipe(() => requestUser(), x => x.fio, fio => writeToFile(fio))
From execution to calculation, a.k.a. thunk:
requestUser() → () => requestUser()
Thunks are lazy!
x && x.obj && x.obj.prop
function pipe(...fns) {
return value => {
var res = value
fns.forEach(currFn => {
res = currFn(res)
})
return res
};
}
pipe(
x => x.obj,
obj => obj.prop
)(x)function pipeWithNullable(...fns) {
return value => {
var res = value;
fns.forEach(currFn => {
if (!isNil(res)) {
res = currFn(res)
}
})
return res
};
}
pipeWithNullable(
x => x.obj,
obj => obj.prop
)(x)x && x.obj && x.obj.prop
class Option {
constructor(value) {
this.value = value
}
then(fn) {
return isNil(this.value)
? this
: new Option(fn(this.value))
}
}var x = {};
var val = new Option(x)
.then(x => x.obj)
.then(obj => obj.prop)class IO {
constructor(calc, args = []) {
this.calc = calc
this.args = args
}
then(fn) {
return new IO(fn, [this])
}
}
var ioAction = new IO(requestUser)
.then(x => x.fio)
.then(fio =>
new IO(() => writeToFile(fio))
)
run(ioAction)ioAction = {
calc: fio => new IO(() => writeToFile(fio)),
args: [
{
calc: x => x.fio,
args: [
{ calc: requestUser, args: [] }
]
}
]
}of, pure, unit — constructor. How do we wrap a value into a monad?flatMap, bind, chain — applier. How do we unwrap a value from a monad?Monad laws:
flatMap(f, of(x)) ≡ f(x)flatMap(of, m) ≡ mflatMap(g, flatMap(f, m)) ≡ flatMap(x => flatMap(g, f(x)), m)Don't break the laws! Beware of the Haskell police!
Promise a.k.a. Task a.k.a. FutureOptional a.k.a. Option a.k.a. MaybeListEither a.k.a. Try a.k.a. ErrorObservableMonads and continuations are isomorphic and equally powerful — Representing Monads
They're just representations of control flow.
Control flow is born from the incompleteness of strict (applicative) evaluation — Lazy Evaluation and Delimited Control

Message passing as the foundation of OOP:
Message passing as the foundation of concurrent computation:
Modern frontend frameworks are built on message passing:
store in Flux, Redux, ngrx/storecomputed in MobX, Vue, EmberEventEmitter in AngularCmd in Elm…and so is the backend:
In Soviet Russia, side effects control you!
blue•function doSomethingAzure() {
// This is a blue function...
}
red•function doSomethingCarnelian() {
// This is a red function...
}
blue•function doSomethingAzure() {
doSomethingCarnelian()•red; // Error — you can't call red inside blue
}
Two different kinds of program code: