Recently, I am learning Working with ADT.

Got some extra thought about State Monad. Basiclly how to thinking in State.

First, we need to know the type of State: State returns Pair with Unit on the left, and state on the right:

State(state => Pair(Unit, state))

We don't need to manully add Pari and Unit type, State provides helper methods for doing this, but it is important to understand.

On the left side, Unit is a variable, types can be very depends on your needs.

On the right side, state has to be a fixed type, you better do NOT change it.

To access right side 'state', we can using 'modify' or 'set' helpers.

To access left side 'Unit', we can using 'get' helper.

One benifit by using State, is that we got lazyness for the function, means we can chain different state transition together.

Let's see an example:

const State = require('crocks/State');

const {get, modify} = State;

// add :: Int -> Int -> Int
const add = x => y => y + x;
// if we want to chain state transform, we need to have a function
// addNickel :: () -> State Int ()
//const addNickel = () => State(s => Pair(Unit(), s + 5))
const addNickel = () => modify(add());
// addDime = () -> State Int ()
const addDime = () => modify(add());
const addQuarter = () => modify(add());

In the example, we define three 'addXX' functions, each add different values.

We can compose them together:

// state :: State Int()
const state = addNickel()
.chain(addDime) // Pair( (), 15 )
.chain(addQuarter) // Pair( (), 40 )
.chain(addQuarter) // Pair( (), 65 )
.chain(addQuarter) // Pair( (), 90 )
.chain(addQuarter) // Pair( (), 115 ) console.log(
state
.runWith()
)

It is important to call 'runWIth', 'execWith' or 'evalWith'... because State is lazy, you need to trigger it. We chain multi state together to get new state, or let's saying we are keep modfiying the state. At this point, we didn't touch the 'Unit' part.

Then why 'Unit' / left side part can be useful?

We can think 'Unit' / left side part is the result of 'state' / right side part after mapping to some logic / function.

For example, we want to build a function, only return True of False, if number is greater than 100, return True, otherwise return False:

// canVend :: Int -> Boolean
const canVend = n => n >= ; console.log(
get()
.map(canVend)
.runWith()
) // False console.log(
get()
.map(canVend)
.runWith()
) // True

For calling 'get()', we are targeting left side part, which is 'Unit', it waiting some mapping function, which can transform state and put result into Unit. If we don't provide any mapping function, 'get()' will just copy the value from 'state':

console.log(
get()
.runWith()
) // Pair(10, 10) console.log(
get()
.map(x => x * )
.runWith()
) // Pair(20, 10) // the same as:
console.log(
get(x => x * )
.runWith()
) // Pair(20, 10)

In 'addNickle' example, we want to only get result in Boolean, if the state is greater than 100 or not, we can keep the state transform part untouched, only chain the getter logic in final state.

// canVend :: Int -> Boolean
const canVend = n => n >= ; // evaluate :: () -> State Int Bool
const evaluate = () => get(canVend); // get().map(fn) === get(fn) // state :: State Int()
const state = addNickel()
.chain(addDime) // Pair( (), 15 )
.chain(addQuarter) // Pair( (), 40 )
.chain(addQuarter) // Pair( (), 65 )
.chain(addQuarter) // Pair( (), 90 )
.chain(addQuarter) // Pair( (), 115 ) console.log(
state
.chain(evaluate)// Pair( true, 115 )
.runWith()
)

Full Code:

---

const State = require('crocks/State');

const {get, modify} = State;

// add :: Int -> Int -> Int
const add = x => y => y + x;// if we want to chain state transform, we need to have a function
// addNickel :: () -> State Int ()
//const addNickel = () => State(s => Pair(Unit(), s + 5))
const addNickel = () => modify(add());
// addDime = () -> State Int ()
const addDime = () => modify(add());
const addQuarter = () => modify(add()); // canVend :: Int -> Boolean
const canVend = n => n >= ; // evaluate :: () -> State Int Bool
const evaluate = () => get(canVend); // get().map(fn) === get(fn) // state :: State Int()
const state = addNickel()
.chain(addDime) // Pair( (), 15 )
.chain(addQuarter) // Pair( (), 40 )
.chain(addQuarter) // Pair( (), 65 )
.chain(addQuarter) // Pair( (), 90 )
.chain(addQuarter) // Pair( (), 115 ) console.log(
state
.chain(evaluate)// Pair( true, 115 )
.runWith()
)

[Functional Programming] Introduction to State, thinking in State的更多相关文章

  1. [Functional Programming] Using ComposeK for both get State and modify State

    We have State like this: const state = { cards: [ { id: "green-square", color: "green ...

  2. [Functional Programming + React] Provide a reasonable default value for mapStateToProps in case initial state is undefined

    For example we have a component, it needs to call 'react-redux' connect function. import { compose, ...

  3. [Functional Programming ADT] Initialize Redux Application State Using The State ADT

    Not only will we need to give our initial state to a Redux store, we will also need to be able to re ...

  4. [Functional Programming Monad] Combine Stateful Computations Using A State Monad

    The true power of the State ADT really shows when we start combining our discrete, stateful transact ...

  5. [Functional Programming Moand] Update The State Of A State Monad (put)

    Stateful computations require the ability for their state to change overtime. We take a look on one ...

  6. [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 Fun ...

  7. [Functional Programming] Transition State based on Existing State using the State ADT (liftState, composeK)

    While sometimes outside input can have influence on how a given stateful transaction transitions, th ...

  8. Beginning Scala study note(4) Functional Programming in Scala

    1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...

  9. Functional programming

    In computer science, functional programming is a programming paradigm, a style of building the struc ...

随机推荐

  1. ubuntu下smokeping安装配置

    0.参考文件 http://wenku.baidu.com/view/950fbb0a79563c1ec5da71b1 http://aaaxiang000.blog.163.com/blog/sta ...

  2. 在Delphi中DBGrid有一个MouseMove事件,当鼠标移动时怎么知道光标在哪个单元格上面

    procedure TForm1.DBGrid1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);var coords:TGr ...

  3. [Asp.net core 2.0]Ueditor 图片上传

    摘要 在项目中要用到富文本编辑器,包含上传图片,插入视频等功能.但ueditor只有.net版本,没有支持core.那么上传等接口就需要自己实现了. 一个例子 首先去百度ueditor官网下载简化版的 ...

  4. UIImageView 详解

    1.//设置 圆角 userhead.layer.masksToBounds = YES; userhead.layer.cornerRadius = 6.0; userhead.layer.bord ...

  5. 基于jQuery的判断iPad、iPhone、Android是横屏还是竖屏的代码

    在ipad.iphone网页开发中,我们很可能需要判断是横屏或者竖屏.下面就来介绍如何用 jQuery 判断iPad.iPhone.Android是横屏还是竖屏的方法 其实主要是通过window.or ...

  6. 法外之徒第一季/全集Braquo迅雷下载

    英文译名 Braquo (第1-2季) (2012-01-05首播)法国.本季看点:<法外之徒>Eddy.Théo.Walter和Roxane私人本是巴黎上塞纳省地区的警察. 因为他们的好 ...

  7. cocos2d-x 3.0 WIN7+VS2012 安卓平台搭建

    ***************************************转载请注明出处:http://blog.csdn.net/lttree************************** ...

  8. pycurl post

    pc = pycurl.Curl() pc.setopt(pycurl.POST, 1) pc.setopt(pycurl.URL, 'http://192.168.0.25:/Image') #pc ...

  9. Python 模块 re (Regular Expression)

    使用 Python 模块 re 实现解析小工具   概要 在开发过程中发现,Python 模块 re(Regular Expression)是一个很有价值并且非常强大的文本解析工具,因而想要分享一下此 ...

  10. Web 前沿——HTML5 Form Data 对象的使用

    原文地址:http://www.cnblogs.com/lhb25/p/html5-formdata-tutorials.html XMLHttpRequest Level 2 添加了一个新的接口-- ...