[Functional Programming] Draw Items from One JavaScript Array to Another using a Pair ADT

使用Pair类型抽取卡牌
本文介绍了一种利用Pair数据类型来有效管理已抽取和未抽取卡牌状态的方法,通过实例展示了如何从十二张卡牌中随机抽取九张,同时保持了代码的清晰和维护性。

We want to be able to pick nine random cards from an array of twelve cards, but can run into problems of keeping both the cards already draw and the cards left to draw from. Tracking two bits of state like this can create some hard to maintain argument gymnastics when creating our functions. Luckily we have a datatype Pair at our disposal that allows us to combine two values in to one value.

We will use this Pair type to model both a draw pile and a remaining pile, and take advantage of a couple special properties of Pair that will allow us to combine two Pair instances in a meaningful way by chaining. Just like we have done time and time again with the State ADT.

 

We have generated array of cards:

[ 
  { 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' } ]

 

By the following code:

const {prop,assoc, pick, State, 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; 

// #region generateCards
const state = {
    colors: [ 'orange', 'green', 'blue', 'yellow' ],
    shapes: [ 'square', 'triangle', 'circle' ]
};

const getState = key => get(prop(key))
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

 

Now what we want to do is split cards array into a Pair,

on the left side pair is the selected card array,

on the rigth side pair is the unselected cards array.

// Splite Cards into two pars
//[Selected Cards] - [UnSelected Cards]

const getAt = index => array => array[index];
const unsetAt = index => array => ([...array.slice(0, index), ...array.slice(index + 1)]);
// Deck :: Pair [Card] [Card]
// drawCardAt :: Integer -> [Card] -> Deck
const drawCardAt = index => fanout(
    getAt(index),
    unsetAt(index)
)

console.log(
    generateCards()
        .map(drawCardAt(0))
        .evalWith(state).fst() 
) // { id: 'orange-square', color: 'orange', shape: 'square' }

console.log(
    generateCards()
        .map(drawCardAt(0))
        .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-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' } ]
*/

Here we use 'fanout' to generate a Pair.

 

Notice that the left side pair is an object, not an array, we need to use 'bimap' to lift left side pair into Array. To do that,. we use 'bimap'

const drawCardAt = index => compose(
    bimap(Array.of, identity),
    fanout(
        getAt(index),
        unsetAt(index)
    )
)

console.log(
    generateCards()
        .map(drawCardAt(0))
        .evalWith(state).fst() 
) // [{ id: 'orange-square', color: 'orange', shape: 'square' }]

 

---

const {prop,assoc, pick, bimap, State, 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; 

// #region generateCards
const state = {
    colors: [ 'orange', 'green', 'blue', 'yellow' ],
    shapes: [ 'square', 'triangle', 'circle' ]
};

const getState = key => get(prop(key))
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

// Splite Cards into two pars
//[Selected Cards] - [UnSelected Cards]

const getAt = index => array => array[index];
const unsetAt = index => array => ([...array.slice(0, index), ...array.slice(index + 1)]);
// Deck :: Pair [Card] [Card]
// drawCardAt :: Integer -> [Card] -> Deck
const drawCardAt = index => compose(
    bimap(Array.of, identity),
    fanout(
        getAt(index),
        unsetAt(index)
    )
)

console.log(
    generateCards()
        .map(drawCardAt(0))
        .map(chain(drawCardAt(2)))
        .map(chain(drawCardAt(3)))
        .map(chain(drawCardAt(4)))
        .evalWith(state).fst() 
) /**
[ { id: 'orange-square', color: 'orange', shape: 'square' },
  { id: 'green-square', color: 'green', shape: 'square' },
  { id: 'green-circle', color: 'green', shape: 'circle' },
  { id: 'blue-triangle', color: 'blue', shape: 'triangle' } ]
*/

console.log(
    generateCards()
        .map(drawCardAt(0))
        .map(chain(drawCardAt(2)))
        .map(chain(drawCardAt(3)))
        .map(chain(drawCardAt(4)))
        .evalWith(state).snd()
    
)
/** 
[ { id: 'orange-triangle', color: 'orange', shape: 'triangle' },
  { id: 'orange-circle', color: 'orange', shape: 'circle' },
  { id: 'green-triangle', color: 'green', shape: 'triangle' },
  { id: 'blue-square', color: 'blue', shape: 'square' },
  { 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' } ]
*/

 

转载于:https://www.cnblogs.com/Answer1215/p/10284743.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值