zoukankan      html  css  js  c++  java
  • [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)
    )
  • 相关阅读:
    elastic-job 新手指南
    最基本的区块链hello world(python3实现)
    python:函数的高级特性
    python高级特性:切片/迭代/列表生成式/生成器
    python:函数中五花八门的参数形式(茴香豆的『回』字有四种写法)
    python:爬虫入门
    python: 序列化/反序列化及对象的深拷贝/浅拷贝
    python中的zip、lambda、map操作
    python面向对象笔记
    RxJava2学习笔记(3)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10274103.html
Copyright © 2011-2022 走看看