[Functional Programming] Pull Many Random Numbers in a Single State ADT Transaction
in State Programming Transaction Random many single Numbers
2023-09-14 09:00:49 时间
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 mreduce
catamorphism 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 * 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) // between :: (Integer, Integer) -> State AppState Integer const between = (min, max) => random() .map(normalize(min, max)); const randomIndex = xs => between(0, 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(0, index), ...array.slice(index + 1) ]; 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 === 1 ? [elem] : repeat(num - 1, elem).concat([elem]); const drawNine = mreduce( Endo, repeat(9, 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) )
相关文章
- Think in Java之Interface
- 5 Generative AI - 5 powerful tools you might use in 2023
- ORA-00316: log string of thread string, type string in header is not log file ORACLE 报错 故障修复 远程处理
- ORA-26652: Capture string did not start properly and is currently in state string ORACLE 报错 故障修复 远程处理
- ORA-28293: No matched Kerberos Principal found in any user entry ORACLE 报错 故障修复 远程处理
- ORA-32010: cannot find entry to delete in SPFILE ORACLE 报错 故障修复 远程处理
- ORA-39784: This direct path operation is not allowed while another is in progress ORACLE 报错 故障修复 远程处理
- ORA-41627: event structure object type in inconsistent state ORACLE 报错 故障修复 远程处理
- ORA-44204: library cache object string.string found in an in-flux state ORACLE 报错 故障修复 远程处理
- ORA-54621: TO_GEOMETRY: TOTAL_DIMENSIONALITY not same as in INIT operation ORACLE 报错 故障修复 远程处理
- ORA-55457: predicate not found in model ORACLE 报错 故障修复 远程处理
- ORA-56934: database property DST_UPGRADE_STATE for datapump job is in an inconsistent state ORACLE 报错 故障修复 远程处理
- ORA-03211: The segment does not exist or is not in a valid state ORACLE 报错 故障修复 远程处理
- ORA-03236: max # extents (string) reached in index string.string subpartition string ORACLE 报错 故障修复 远程处理
- ORA-06608: LU6.2 Driver: Reset occurred in receive state ORACLE 报错 故障修复 远程处理
- ORA-08451: invalid specification of DB in picture mask ORACLE 报错 故障修复 远程处理
- ORA-16170: Terminal recovery may have left the database in an inconsistent state ORACLE 报错 故障修复 远程处理
- ORA-19238: XPTY0018 – It is a type error if the result of the last step in a path expression contains both nodes and atomic values ORACLE 报错 故障修复 远程处理
- PostgreSQL 54023: too_many_arguments55000 object_not_in_prerequisite_state 报错 故障修复 远程处理
- PICE(1):Programming In Clustered Environment – 集群环境内编程模式详解编程语言
- MySQL删除IN操作: 简易指南(mysql删除in)
- 进行字符串比较使用Oracle IN运算符比较字符串(oracle使用in)
- MySQL中的IN运算符技巧(mysql查in)
- 关键字使用Oracle中的Replace函数替代IN关键字(oracle替代in)
- MySQL中使用IN子查询的技巧(mysql子查询in)
- MySQL查询优化:从IN中获取更高性能(mysql查询优化in)
- Efficient File Retrieval in Linux: Tips and Tricks for LightningFast Searches(linux快速查找文件)
- Exploring the Functionality of PFN in the Linux Operating System(linuxpfn)
- Oracle中使用IN函数查找元素(oracle 函数 in)
- MySQL中的Out和In操作一个简单的指南(mysql中out in)
- MySQL使用IN查询时数量超限问题的解决方法(mysql中in超过数量)
- MySQL中使用in语句的效率问题(MySQL中in效率)
- 深入分析MySQL中IN语句的性能问题(mysql中in性能分析)
- MYSQL中IN关键字如何高效处理大量数据(mysql中in关键字)
- 避免使用MySQL中的IN操作,提升查询效率(mysql 不使用in)
- 解决MySQL中in子查询问题(mysql不能in子查询)
- 查询Oracle中使用IN关键字查询多个值的方法(oracle中in多个值)
- 替代Oracle不建议用in取代(oracle不建议用in)
- 查询Oracle中模糊查询的奇妙之旅(oracle in 模糊)
- acle joinOracle IN与Oracle Join的差异探讨(oracle in与or)