[Functional Programming] Pull Many Random Numbers in a Single State ADT Transaction
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) )
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-01-22 [React] Optimistic UI update in React using setState()
2018-01-22 [Javascript] Required function arguments in Javascript
2017-01-22 [Vue] Update Attributes, Classes and Styles in Vue.js with v-bind