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. LPC18xx/43xx OTP Controller driver

    LPC18xx/43xx OTP Controller driver /* * @brief LPC18xx/43xx OTP Controller driver * * @note * Copyri ...

  2. systemtap跟踪C

    1.[root@localhost ~]# rpm -qi  glibcName        : glibc                        Relocations: (not rel ...

  3. 怎么发现RAC环境中'library cache pin'等待事件的堵塞者(Blocker)?

    怎么发现RAC环境中的'library cache pin'等待事件的堵塞者(Blocker) 參考自 How to Find the Blocker of the 'library cache pi ...

  4. Revit API创建墙的保温层修改墙厚度

    start [Transaction(TransactionMode.Manual)] [Regeneration(RegenerationOption.Manual)]  / ;         ; ...

  5. SVN的管理方式和git的管理方式

    SVN是集中式的管理方式.大致流程如下: 1.从服务器上将整个项目代码检出到本地电脑硬盘中(一般来说,是从主分支上下载的代码).2.然后在svn服务器中建立新的开发分支,将硬盘中的代码提交到该开发分支 ...

  6. 交叉编译Python-2.7.13到ARM(aarch64)平台

    方法跟交叉编译Python-2.7.13到ARM(aarch32)平台基本一样, 不同的地方只是把工具链换成编译aarch64的工具链,这里可以参考用qemu搭建aarch64学习环境. 创建目录: ...

  7. 在ASP.NET MVC中使用typeahead.js支持预先输入,即智能提示

    使用typeahead.js可以实现预先输入,即智能提示,本篇在ASP.NET MVC下实现.实现效果如下: 首先是有关城市的模型. public class City { public int Id ...

  8. function, new function, new Function

    函数是JavaScript中很重要的一个语言元素,并且提供了一个function关键字和内置对象Function,下面是其可能的用法和它们之间的关系.    使用方法一:  var foo01 = f ...

  9. 查看webservice服务下的所有方法和参数类型

    方法:直接在IE浏览器中输入webservice的地址,查看返回的XML数据即可. 效果如下:

  10. C#编程(三十七)----------结构比较

    结构比较 数组和元组都实现接口IStructuralEquatable和IStructuralComparable.这两个接口不仅可以比较引用,还可以比较内容.这些接口都是显示实现的,所以在使用时需要 ...