[Functional Programming] Randomly Pull an Item from an Array with the State ADT (Pair)
Functor composition is a powerful concept that arises when we have one Functor nested in another Functor. It becomes even more powerful when both of those are Chains, allowing us to apply each Functor’s special properties and effects for a given computation.
We witness this power first hand by combining our beloved State with a Pair type mixing the ability to randomly pick an index from an Array using State and use it to draw an element from the Array. We will build up to an easy to use interface that allows us to pull as many elements as we need, by chaining on single State transaction.
// 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 {prop,assoc, 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' ],
seed: Date.now()
};
const liftState = (fn) => compose(
of, fn
);
const getState = key => get(prop(key))
// #region random
// nextSeed :: Integer -> Integer
const nextSeed = seed =>
(seed * + ) & 0x7fffffff
// value :: Integer -> Number
const value = seed =>
(seed >>> ) / 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(, 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(, index),
...array.slice(index + )
];
const drawCardAt = index => fanout(getAt(index), unsetAt(index));
// #endregion
// getDeck :: () -> State AppState Deck
const getDeck = () => generateCards()
.map(xs => Pair([], xs));
// draw :: Integer -> Deck -> Deck
const draw = compose(
chain,
drawCardAt
);
// const draw = index => deck => deck.chain(drawCardAt(index))
// drawRandom :: Deck -> State AppState Deck
const drawRandom = converge(
liftA2(draw),
compose(
randomIndex,
snd
),
liftState(identity)
)
console.log(
getDeck()
.chain(drawRandom)
.chain(drawRandom)
.chain(drawRandom)
.chain(drawRandom)
.evalWith(state).fst()
)
[Functional Programming] Randomly Pull an Item from an Array with the State ADT (Pair)的更多相关文章
- Beginning Scala study note(4) Functional Programming in Scala
1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...
- a primary example for Functional programming in javascript
background In pursuit of a real-world application, let’s say we need an e-commerce web applicationfo ...
- Functional programming
In computer science, functional programming is a programming paradigm, a style of building the struc ...
- Functional Programming without Lambda - Part 2 Lifting, Functor, Monad
Lifting Now, let's review map from another perspective. map :: (T -> R) -> [T] -> [R] accep ...
- Functional Programming without Lambda - Part 1 Functional Composition
Functions in Java Prior to the introduction of Lambda Expressions feature in version 8, Java had lon ...
- Java 中的函数式编程(Functional Programming):Lambda 初识
Java 8 发布带来的一个主要特性就是对函数式编程的支持. 而 Lambda 表达式就是一个新的并且很重要的一个概念. 它提供了一个简单并且很简洁的编码方式. 首先从几个简单的 Lambda 表达式 ...
- Functional programming idiom
A functional programming function is like a mathematical function, which produces an output that typ ...
- 关于函数式编程(Functional Programming)
初学函数式编程,相信很多程序员兄弟们对于这个名字熟悉又陌生.函数,对于程序员来说并不陌生,编程对于程序员来说也并不陌生,但是函数式编程语言(Functional Programming languag ...
- Functional Programming 资料收集
书籍: Functional Programming for Java Developers SICP(Structure and Interpretation of Computer Program ...
随机推荐
- 【C++】指针和new相关
看黄邦勇帅的笔记. 指针和new之前觉得已经掌握的很好了,可是看了资料还是get到了新知识.记录一下. 1.指针只支持 4 种算术运算符:++,――,+,-.指针只能与整数加减.指针运算的原则是:每当 ...
- 【python】python2.x 与 python3.x区别对照+缩进错误解决方法
仅仅列出我用到的,不全. 划重点: 1. urllib2 用 urllib.request 代替 2. urllib.urlencode 用 urllib.parse.urlencode 代替 3. ...
- JDK 动态代理 源码简单分析
代理的作用就是在访问真实对象之前或者之后可以额外加入一些操作. JDK 的动态代理 只需要 5 步. 真实对象必须要实现接口,首先创建一个接口 public interface HelloWorld ...
- IIS7.0添加IP地址和域名限制
IIS7.0默认安装是没有“IP地址和域名限制”功能的,需要我们自己选择安装 1.windows系统的添加方式 控制面板--程序与功能--启用或关闭windows功能--internat inform ...
- sybase ase 重启
sybase ase 重启 https://blog.csdn.net/davidmeng10/article/details/50344305 https://blog.csdn.net/wengy ...
- AC日记——Success Rate codeforces 807c
Success Rate 思路: 水题: 代码: #include <cstdio> #include <cstring> #include <iostream> ...
- 【转.解析清晰】你真明白 Python 装饰器么?
原文出处: 武沛齐 装饰器是程序开发中经常会用到的一个功能,用好了装饰器,开发效率如虎添翼,所以这也是Python面试中必问的问题,但对于好多小白来讲,这个功能 有点绕,自学时直接绕过去了, ...
- scrapy 最新版本中文文档地址
http://scrapy-chs.readthedocs.org/zh_CN/latest/
- 曼哈顿距离、欧几里得距离、闵氏距离(p→∞为切比雪夫距离)
曼哈顿距离: 是由十九世纪的赫尔曼·闵可夫斯基所创词汇 ,是种使用在几何度量空间的几何学用语,用以标明两个点在标准坐标系上的绝对轴距总和. 曼哈顿距离——两点在南北方向上的距离加上在东西方向上的距离, ...
- 将csv格式的数据文件导入/导出数据库+添加新的字段
最近一直忙于实验室的事情,没有好好更新博客,在抓包的过程中,遇到了很多问题. 因为我常用Wireshark将抓包信息导出为csv文件,这里简单mark一下将csv文件导入/导出到数据库的2种方法: 一 ...