DAY 28
0
Software Development

## Day 28 - State Monad III

Applicative Functor

``````const State = (run) => ({
run,
map: (f) =>
State((a) => {
const [y, s] = run(a);
return [f(y), s];
}),
chain: (f) =>
State((x) => {
const [y, s] = run(x);
return f(y).run(s);
}),
ap: (m) =>
State((x) => {
const [y, s] = run(x);
return m.map(y).run(s);
}),
});
``````

``````State.of(1).map(R.add).ap(State.of(1)).run() // [3, undefined]
``````

### Travserable

``````Array.prototype.traverse = function (T, f) {
return this.reduce(
(acc, val) =>
f(val)
.map((x) => (y) => y.concat(x))
.ap(acc),
T.of([])
);
};
``````

``````const generator = (seed) => {
const nextSeed = (seed * 1103515245 + 12345) & 0x7fffffff;
return [nextSeed, nextSeed];
};

const value = (seed) => (seed >>> 16) / 0x7fff;

const normalize = (min, max) => (x) => Math.floor(x * (max - min)) + min;

const randomInRange = (min, max) =>
State(generator).map(value).map(normalize(min, max));

const randomFrom = (from) =>
randomInRange(0, from.length).map((index) => from[index]);

const FisrtRandom = randomFrom(['FP', 'OOP', 'BOTH']);
const MiddleRandom = randomFrom(['IS', 'ARE']);
const LastRandom = randomFrom(['GOOD', 'SUCK']);

const combineIt = [FisrtRandom, MiddleRandom, LastRandom]
``````

``````const seed = 1;

combineIt.traverse(State, R.identity)
.map(([x, y, z]) => `\${x} \${y} \${z}`)
.run(seed);

// ["FP IS SUCK", 333417792]
``````

Oops! 怎麼會這樣... 突然覺得變搞笑文章系列，Anyway, That's it for today!

## Reference

### 1 則留言

1
juck30808
iT邦新手 3 級 ‧ 2021-10-14 12:11:26