We have the ability to select a single random card from a pile of twelve cards, but we would like to pull a total of nine. Not only that, we would like to match the same transition functions we have been writing all along.

Lucky for use there are three types of functions, or morphisms that we can use to get us everything we need. We use an anamorphism to expand our one function into a list of nine functions. Each of these functions are endomorphisms, so we can use the mreducecatamorphism with the Endo Monoid to fold them down into one function that we can use to get this action into our state transactions.

const { mreduce, prop,assoc, Endo, Pair, pick, bimap, State, snd, identity, omit, curry, filter, fanout, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
const {get, modify, of} = State; const state = {
colors: [ 'orange', 'green', 'blue', 'yellow' ],
shapes: [ 'square', 'triangle', 'circle' ],
cards: null,
seed: Date.now()
}; const liftState = (fn) => compose(
of, fn
);
const getState = key => get(prop(key)) // #region random
// nextSeed :: Integer -> Integer
const nextSeed = seed =>
(seed * + ) & 0x7fffffff // value :: Integer -> Number
const value = seed =>
(seed >>> ) / 0x7fff // normalize :: (Integer, Integer) -> Number -> Integer
const normalize = (min, max) =>
x => Math.floor(x * (max - min)) + min // getNextSeed :: () -> State AppState Integer
const getNextSeed = () =>
get(({ seed }) => nextSeed(seed)) // updateSeed :: Integer -> State AppState ()
const updateSeed = seed =>
modify(assoc('seed', seed)) // nextValue :: Integer -> State AppState Number
const nextValue = converge(
liftA2(constant),
liftState(value),
updateSeed
) // random :: () -> State AppState Number
const random =
composeK(nextValue, getNextSeed) // between :: (Integer, Integer) -> State AppState Integer
const between = (min, max) =>
random()
.map(normalize(min, max)); const randomIndex = xs => between(, xs.length);
// #endregion // #region generate const getColors = () => getState('colors').map(option([]));
const getShapes = () => getState('shapes').map(option([]));
const buildCard = curry((color, shape) => ({
id: `${color}-${shape}`,
color,
shape
}));
const buildCards = liftA2(buildCard);
const generateCards = converge(
liftA2(buildCards),
getColors,
getShapes
); // #endregion // #region draw
const getAt = index => array => Array.of(array[index]);
const unsetAt = index => array => [
...array.slice(, index),
...array.slice(index + )
];
const drawCardAt = index => fanout(getAt(index), unsetAt(index));
// #endregion // getDeck :: () -> State AppState Deck
const getDeck = () => generateCards()
.map(xs => Pair([], xs));
/**
Pair(
[ ],
[ { id: "orange-square", color: "orange", shape: "square" }, { id: "orange-triangle", color: "orange", shape: "triangle" }, { id: "orange-circle", color: "orange", shape:
"circle" }, { id: "green-square", color: "green", shape: "square" }, { id: "green-triangle", color: "green", shape: "triangle" }, { id: "green-circle", color: "green", shape: "circle" }, { id: "blue-square", color: "blue", shape: "square" }, { id: "blue-triangle", color: "blue", shape: "triangle" }, { id: "blue-circle", color: "blue", shape: "circle" }, { id: "yellow-square", color: "yellow", shape: "square" }, { id: "yellow-triangle", color: "yellow", shape: "triangle" }, { id: "yellow-circle", color: "yellow", shape: "circle" } ]
)
*/
// draw :: Integer -> Deck -> Deck
const draw = compose(
chain,
drawCardAt
);
// const draw = index => deck => deck.chain(drawCardAt(index)) // drawRandom :: Deck -> State AppState Deck
// From the right side pair, get a random index, then draw the card by index
const drawRandom = converge(
liftA2(draw),
compose(
randomIndex,
snd
),
liftState(identity)
) console.log(
getDeck()
.chain(drawRandom)
.chain(drawRandom)
.chain(drawRandom)
.evalWith(state).fst()
)
/**
* [ { id: 'orange-square', color: 'orange', shape: 'square' },
{ id: 'blue-triangle', color: 'blue', shape: 'triangle' },
{ id: 'blue-square', color: 'blue', shape: 'square' } ]
*/
console.log(
getDeck()
.chain(drawRandom)
.chain(drawRandom)
.chain(drawRandom)
.evalWith(state).snd()
)
/**
[ { id: 'orange-triangle', color: 'orange', shape: 'triangle' },
{ id: 'orange-circle', color: 'orange', shape: 'circle' },
{ id: 'green-square', color: 'green', shape: 'square' },
{ id: 'green-triangle', color: 'green', shape: 'triangle' },
{ id: 'green-circle', color: 'green', shape: 'circle' },
{ id: 'blue-circle', color: 'blue', shape: 'circle' },
{ id: 'yellow-square', color: 'yellow', shape: 'square' },
{ id: 'yellow-triangle', color: 'yellow', shape: 'triangle' },
{ id: 'yellow-circle', color: 'yellow', shape: 'circle' } ]
*/ const repeat = (num, elem) =>
num ===
? [elem]
: repeat(num - , elem).concat([elem]); const drawNine = mreduce(
Endo,
repeat(, chain(drawRandom))
); const drawFromDeck = compose(
drawNine, getDeck
)
const over = (key, fn) => modify(mapProps({[key]: fn}));
const setCards = deck => over('cards', constant(deck.fst())) const pickCards = composeK(setCards, drawFromDeck) console.log(
pickCards()
.execWith(state)
)

[Functional Programming] Pull Many Random Numbers in a Single State ADT Transaction的更多相关文章

  1. 2017 ACM-ICPC, Universidad Nacional de Colombia Programming Contest K - Random Numbers (dfs序 线段树+数论)

    Tamref love random numbers, but he hates recurrent relations, Tamref thinks that mainstream random g ...

  2. [Functional Programming] Using JS, FP approach with Arrow or State Monad

    Using Naive JS: const {modify, get} = require('crocks/State'); const K = require('crocks/combinators ...

  3. [Functional Programming Monad] Refactor Stateful Code To Use A State Monad

    When we start to accumulate functions that all work on a given datatype, we end up creating a bunch ...

  4. [Functional Programming] Randomly Pull an Item from an Array with the State ADT (Pair)

    Functor composition is a powerful concept that arises when we have one Functor nested in another Fun ...

  5. Functional programming

    In computer science, functional programming is a programming paradigm, a style of building the struc ...

  6. Generating Gaussian Random Numbers(转)

    Generating Gaussian Random Numbers http://www.taygeta.com/random/gaussian.html This note is about th ...

  7. Beginning Scala study note(4) Functional Programming in Scala

    1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...

  8. Functional Programming without Lambda - Part 2 Lifting, Functor, Monad

    Lifting Now, let's review map from another perspective. map :: (T -> R) -> [T] -> [R] accep ...

  9. Functional Programming without Lambda - Part 1 Functional Composition

    Functions in Java Prior to the introduction of Lambda Expressions feature in version 8, Java had lon ...

随机推荐

  1. [ Openstack ] OpenStack-Mitaka 高可用之 认证服务(keystone)

    目录 Openstack-Mitaka 高可用之 概述    Openstack-Mitaka 高可用之 环境初始化    Openstack-Mitaka 高可用之 Mariadb-Galera集群 ...

  2. ie_placeholder最佳兼容方案

    https://gitee.com/hustcc/placeholder.js巧妙的使用了canvas.toDataURL(),动态生成了一个背景图,可以作为兼容IE9-的placeholder方案. ...

  3. 《Java编程思想》笔记 第五章 初始化与清理

    1.构造器 因为创建一个类的对象构造器就会自动执行,故初始化某些东西特好 2.方法重载 方法名相同,参数列表不同. 2.1 区分重载方法 方法重载后区别不同方法的就是方法签名 -->参数类型和个 ...

  4. java javac 的区别

    cmd中,执行java命令与javac命令的区别: javac:是编译命令,将java源文件编译成.class字节码文件. 例如:javac hello.java 将生成hello.class文件 j ...

  5. ACM数论-欧几里得与拓展欧几里得算法

    欧几里德算法又称辗转相除法,用于计算两个整数a,b的最大公约数. 基本算法:设a=qb+r,其中a,b,q,r都是整数,则gcd(a,b)=gcd(b,r),即gcd(a,b)=gcd(b,a%b). ...

  6. Codeforces 855C - Helga Hufflepuff's Cup

    855C - Helga Hufflepuff's Cup 题意 要求构建一棵树,树上至多可以存在 \(x\) 个权值为 \(k\) 的重要点,且与重要点连边的点的权值必须小于 \(k\),问有多少种 ...

  7. 洛谷——P2421 A-B数对(增强版)

    题目背景 woshiren在洛谷刷题,感觉第一题:求两数的和(A+B Problem)太无聊了,于是增加了一题:A-B Problem,难倒了一群小朋友,哈哈. 题目描述 给出N 个从小到大排好序的整 ...

  8. UVA 839 Not so Mobile (递归建立二叉树)

    题目连接:http://acm.hust.edu.cn/vjudge/problem/19486 给你一个杠杆两端的物体的质量和力臂,如果质量为零,则下面是一个杠杆,判断是否所有杠杆平衡. 分析:递归 ...

  9. [BZOJ3551][ONTAK2010]Peaks(加强版)(Kruskal重构树,主席树)

    3551: [ONTAK2010]Peaks加强版 Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 2438  Solved: 763[Submit][ ...

  10. Asp.Net MVC part6 WebAPI

    两种web服务SOAP风格:基于方法,产品是WebServiceREST风格:基于资源,产品是WebAPI可以返回json.xml类型的数据对于数据的增.删.改.查,提供相对的资源操作,按照请求的类型 ...