[Javascript] Use a Pure RNG with the State ADT to Select an Element from State
The resultant in a State ADT instance can be used as a means of communication between different stateful transactions. It can be used to read and transform a portion of our state into a form that another transaction is dependent on. This allows us to only keep what is needed state, without filling it with calculations that are only needed for one or few transactions.
We take can take advantage of this by pulling not only a random number using the seed from our state, but also pulling a list of card and filtering them, to randomly select one from our calculated state. Then we use the resultant to store the calculation before we save the result to state.
Code for Random generator is here, which is not so important to this blog.
const {prop,assoc, State, identity, omit, curry, filter, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
const {get, modify, of} = State;
const state = {
cards: [
{id: 'green-square', color: 'green', selected: true, shape: 'square'},
{id: 'orange-square', color: 'orange', shape: 'square'},
{id: 'blue-triangle', color: 'blue', shape: 'triangle'}
],
hint: null,
seed: Date.now()
}
// #region helper
const liftState = fn => compose(
of,
fn
)
// nextSeed :: Integer -> Integer
const nextSeed = seed =>
(seed * 1103515245 + 12345) & 0x7fffffff
// value :: Integer -> Number
const value = seed =>
(seed >>> 16) / 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)
// #endregion
// between :: (Integer, Integer) -> State AppState Integer
const between = (min, max) =>
random()
.map(normalize(min, max));
The only important piece is 'bewteen' function, which can generate the Number between a min & max range.
The idea for what we are going to achieve is that:
- Select all the unselected cards
- Randomly choose one unselected card by using random function
- Set the hint according to the selected card.
First, select all the unselected cards:
const selectState = (key, fn) => get(
compose(
map(fn),
prop(key)
)
)
const unselected = ({selected}) => !selected;
const getUnselectedCards = () => selectState('cards', filter(unselected)).map(option([]))
Second: Rnadomly choose one unselected card by using random function:
// randomIndex :: [a] -> State AppState a
const randomIndex = arr => between(0, arr.length)
const getAt = index => arr => arr[index];
const pickCard = converge(
liftA2(getAt),
randomIndex,
liftState(identity)
)
Last, Set the hint according to the selected card:
const over = (key, fn) => modify(
mapProps({[key]: fn})
)
const toHint = pick(['color', 'shape'])
// setHint :: Card -> State AppState()
const setHint = card => over('hint', constant(toHint(card)))
const nextHint = composeK(
setHint,
pickCard,
getUnselectedCards
)
-----------------
const {prop,assoc, pick, State, identity, omit, curry, filter, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
const {get, modify, of} = State;
const state = {
cards: [
{id: 'green-square', color: 'green', selected: true, shape: 'square'},
{id: 'orange-square', color: 'orange', shape: 'square'},
{id: 'blue-triangle', color: 'blue', shape: 'triangle'}
],
hint: null,
seed: Date.now()
}
// #region helper
const liftState = fn => compose(
of,
fn
)
// nextSeed :: Integer -> Integer
const nextSeed = seed =>
(seed * 1103515245 + 12345) & 0x7fffffff
// value :: Integer -> Number
const value = seed =>
(seed >>> 16) / 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)
// #endregion
// between :: (Integer, Integer) -> State AppState Integer
const between = (min, max) =>
random()
.map(normalize(min, max));
// Get all unselected card
// Randomly choose an unselected Card
// Set hint
const selectState = (key, fn) => get(
compose(
map(fn),
prop(key)
)
)
const unselected = ({selected}) => !selected;
const getUnselectedCards = () => selectState('cards', filter(unselected)).map(option([]))
// randomIndex :: [a] -> State AppState a
const randomIndex = arr => between(0, arr.length)
const getAt = index => arr => arr[index];
const pickCard = converge(
liftA2(getAt),
randomIndex,
liftState(identity)
)
const over = (key, fn) => modify(
mapProps({[key]: fn})
)
const toHint = pick(['color', 'shape'])
// setHint :: Card -> State AppState()
const setHint = card => over('hint', constant(toHint(card)))
const nextHint = composeK(
setHint,
pickCard,
getUnselectedCards
)
console.log(
nextHint()
.execWith(state)
)
[Javascript] Use a Pure RNG with the State ADT to Select an Element from State的更多相关文章
- [Functional Programming ADT] Adapt Redux Actions/Reducers for Use with the State ADT
By using the State ADT to define how our application state transitions over time, we clear up the ne ...
- [Functional Programming ADT] Create State ADT Based Reducers (applyTo, Maybe)
The typical Redux Reducer is function that takes in the previous state and an action and uses a swit ...
- [React + Functional Programming ADT] Connect State ADT Based Redux Actions to a React Application
With our Redux implementation lousy with State ADT based reducers, it is time to hook it all up to a ...
- [Functional Programming ADT] Create a Redux Store for Use with a State ADT Based Reducer
With a well defined demarcation point between Redux and our State ADT based model, hooking up to a R ...
- [Functional Programming ADT] Initialize Redux Application State Using The State ADT
Not only will we need to give our initial state to a Redux store, we will also need to be able to re ...
- [Functional Programming ADT] Combine Multiple State ADT Based Redux Reducers
Redux provides a convenient helper for combining many reducers called combineReducer, but it focuses ...
- [Functional Programming] Combine Multiple State ADT Instances with the Same Input (converge(liftA2(constant)))
When combining multiple State ADT instances that depend on the same input, using chain can become qu ...
- [Functional Programming] Read and Transform Values from a State ADT’s State (get)
Many times we need to access and transform state, either in part or in full, to be used when calcula ...
- [Functional Programming] Combine State Dependent Transactions with the State ADT (composeK to replace multi chian call)
When developing a Finite State Machine, it is often necessary to apply multiple transitions in tande ...
随机推荐
- python--selectors
import socket from selectors import DefaultSelector, EVENT_READ, EVENT_WRITE # 会根据当前的操作系统选择一个合适的文件描述 ...
- PhpExcel一些使用方法
下面是总结的几个使用方法include 'PHPExcel.php';include 'PHPExcel/Writer/Excel2007.php';//或者include 'PHPExcel/Wri ...
- 关于oracle的连接时ORA-12519错误的解决方案
系统在运行时出现了ORA-12519的错误,无法连接数据库,后来在网上找了下,找到了如下的解决方法,共享下. OERR: ORA-12519 TNS:no appropriate service ha ...
- KVM(三)I/O 全虚拟化和准虚拟化
在 QEMU/KVM 中,客户机可以使用的设备大致可分为三类: 1. 模拟设备:完全由 QEMU 纯软件模拟的设备. 2. Virtio 设备:实现 VIRTIO API 的半虚拟化设备. 3. PC ...
- k8s的chart学习(下)
1.开发自己的chart Kubernetes 给我们提供了大量官方 chart,不过要部署微服务应用,还是需要开发自己的 chart,下面就来实践这个主题. 1.1创建 chart 执行 helm ...
- 测试social_navigation_layers
目标:测试social_navigation_layers 方法: 使用move_base接口启动costmap_2d 这样就能直接用configure方法来进行测试不用自己写代码 一.启动move_ ...
- SVN的配置和使用
1.安装前必备 获取 Subversion 服务器程序 到官方网站 http://subversion.tigris.org/ 我下的是CollabNetSubversion-server-1. ...
- UESTC 1599.wtmsb-STL(priority_queue)
wtmsb Time Limit: 1000/100MS (Java/Others) Memory Limit: 131072/131072KB (Java/Others) 这天,AutSky_Jad ...
- Codeforces 811 C. Vladik and Memorable Trip
C. Vladik and Memorable Trip time limit per test 2 seconds memory limit per test 256 megabytes inp ...
- php中parse_url函数的源码及分析(scheme部分)
前言 看师傅们的文章时发现,parse_url出现的次数较多,单纯parse_url解析漏洞的考题也有很多,在此研究一下源码(太菜了看不懂,待日后再补充Orz) 源码 在ext/standard/ur ...