Monads allow you to nest computations. They are a pointed functor that adds mjoin and chain functions to combine other functors. Brian shows a number of code examples of different monads in action.

functions: "mjoin", "chain"

mjoin:

var setSearchInput = function(x){ return ("#input").val(x); }.toIO()
var getSearchTerm = function(){ return getParam("term", location.search) }.toIO()
var initSearchForm = compose(mjoin, map(setSearchInput), getSearchTerm) initSearchForm()
//=> IO(Dom) runIO(initSearchForm())

"getSearchTerm" return an IO, so in "setSearchInput" we need to use map(), but itself will return another IO, so the result is IO(IO()), then we apply mjoin, the result will be "IO()".

chain:

var chain = function(f){
return compose(mjoin, map(f))
}
var setSearchInput = function(x){ return ("#input").val(x); }.toIO()
var getSearchTerm = function(){ return getParam("term", location.search) }.toIO()
var initSearchForm = compose(chain(setSearchInput), getSearchTerm) initSearchForm()
//=> IO(Dom) runIO(initSearchForm())
var sendToServer = httpGet('/upload')
var uploadFromFile = compose(chain(sendToServer), chain(readFile), askUser) uploadFromFile('what file?').fork(logErr, alertSuccess)
requirejs.config({
shim: {},
paths: {
domReady: 'https://cdnjs.cloudflare.com/ajax/libs/require-domReady/2.0.1/domReady.min',
ramda: '//cdnjs.cloudflare.com/ajax/libs/ramda/0.8.0/ramda.min',
maybe: 'http://looprecur.com/hostedjs/v2/maybe',
io: 'http://looprecur.com/hostedjs/v2/io',
future: 'http://looprecur.com/hostedjs/v2/data.future.umd',
hcjs: 'http://looprecur.com/hostedjs/v2/hcjs'
}
}); require(
[
'ramda',
'maybe',
'io',
'future',
'hcjs',
'domReady!'
],
function (_, Maybe, io, Future) {
console.clear(); var runIO = io.runIO; // Exercise 1
// ==========
// Use safeGet and mjoin or chain to safetly get the street name
console.log("--------Start exercise 1--------"); var safeGet = _.curry(function (x, o) {
return Maybe(o[x]);
});
var user = {
id: ,
name: "Albert",
address: {
street: {
number: ,
name: 'Walnut St'
}
}
};
function log (x){
console.log(x.toString());
return x;
} var ex1 = compose(mjoin, map(safeGet('name')) ,mjoin, map(safeGet('street')) ,safeGet('address'));
var ex1 = compose(chain(safeGet('name')), chain(safeGet('street')), safeGet('address'));
assertEqual(Maybe('Walnut St'), ex1(user));
console.log("exercise 1...ok!"); // Exercise 2
// ==========
// Use monads to get the href, then purely log it. console.log("--------Start exercise 2--------"); var getHref = function () {
return location.href;
}.toIO();
var pureLog = function (x) {
console.log(x);
return x;
}.toIO(); var ex2 = compose(chain(pureLog), getHref); assertEqual("http://run.jsbin.com/runner", runIO(ex2(null)));
console.log("exercise 2...ok!"); // Exercise 3
// ==========
// Use monads to first get the Post with getPost(), then pass it's id in to getComments().
console.log("--------Start exercise 3--------"); var ex3 = compose(chain(compose(getComments ,_.get('id'))) , getPost);
var ex3 = compose(mjoin, map(compose(getComments, _.get('id'))), getPost) ex3().fork(log, function (res) {
assertEqual(, res.length);
console.log("exercise 3...ok!");
}); // HELPERS
// ===================== function getPost(i) {
return new Future(function (rej, res) {
setTimeout(function () {
res({
id: i,
title: 'Love them futures'
});
}, );
});
} function getComments(i) {
return new Future(function (rej, res) {
setTimeout(function () {
res(["This class should be illegal", "Monads are like space burritos"]);
}, );
});
} });

[Javascript] Monads的更多相关文章

  1. 翻译连载 |《你不知道的JS》姊妹篇 |《JavaScript 轻量级函数式编程》- 引言&前言

    原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 译者团队(排名不分先后):阿希.blueken.brucec ...

  2. JavaScript 风格指南

    来源于: https://github.com/alivebao/clean-code-js 目录 介绍 变量 函数 对象和数据结构 类 测试 并发 错误处理 格式化 注释 介绍 作者根据 Rober ...

  3. 给 JavaScript 开发者讲讲函数式编程

    本文译自:Functional Programming for JavaScript People 和大多数人一样,我在几个月前听到了很多关于函数式编程的东西,不过并没有更深入的了解.于我而言,可能只 ...

  4. 一文带你了解JavaScript函数式编程

    摘要: 函数式编程入门. 作者:浪里行舟 Fundebug经授权转载,版权归原作者所有. 前言 函数式编程在前端已经成为了一个非常热门的话题.在最近几年里,我们看到非常多的应用程序代码库里大量使用着函 ...

  5. Clean Code of JavaScript

    Clean Code of JavaScript 代码简洁之道 JavaScript 版 https://github.com/ryanmcdermott/clean-code-javascript ...

  6. 前端大牛带你了解JavaScript 函数式编程

    前言 函数式编程在前端已经成为了一个非常热门的话题.在最近几年里,我们看到非常多的应用程序代码库里大量使用着函数式编程思想. 本文将略去那些晦涩难懂的概念介绍,重点展示在 JavaScript 中到底 ...

  7. JavaScript之父Brendan Eich,Clojure 创建者Rich Hickey,Python创建者Van Rossum等编程大牛对程序员的职业建议

    软件开发是现时很火的职业.据美国劳动局发布的一项统计数据显示,从2014年至2024年,美国就业市场对开发人员的需求量将增长17%,而这个增长率比起所有职业的平均需求量高出了7%.很多人年轻人会选择编 ...

  8. javascript中的Array对象 —— 数组的合并、转换、迭代、排序、堆栈

    Array 是javascript中经常用到的数据类型.javascript 的数组其他语言中数组的最大的区别是其每个数组项都可以保存任何类型的数据.本文主要讨论javascript中数组的声明.转换 ...

  9. Javascript 的执行环境(execution context)和作用域(scope)及垃圾回收

    执行环境有全局执行环境和函数执行环境之分,每次进入一个新执行环境,都会创建一个搜索变量和函数的作用域链.函数的局部环境不仅有权访问函数作用于中的变量,而且可以访问其外部环境,直到全局环境.全局执行环境 ...

随机推荐

  1. Python easy_install

    系统中有高版本的Python, 直接pip3 install ipcalc安装,都是装到高版本的Python 系统默认的Python是2.7.6,现在想装到默认版本中,可以使用easy_install ...

  2. 解决32位plsql客户端连接不64位Oracle11g上数据库

    一.解决方案 因为本人安装的是64位的Oracle,plsql 是32位的故连接不上.网上有方法能连接. 1. 文件下载 下载PLSQL_Developer地址 http://pan.baidu.co ...

  3. 使用HttpURLConnection下载文件时出现 java.io.FileNotFoundException彻底解决办法

    使用HttpURLConnection下载文件时经常会出现 java.io.FileNotFoundException文件找不到异常,下面介绍下解决办法 首先设置tomcat对get数据的编码:con ...

  4. 《Python 学习手册4th》 第十五章 文档

    ''' 时间: 9月5日 - 9月30日 要求: 1. 书本内容总结归纳,整理在博客园笔记上传 2. 完成所有课后习题 注:“#” 后加的是备注内容 (每天看42页内容,可以保证月底看完此书) “重点 ...

  5. 用Vmware安装centos5

    Vmware安装过程就不详述了,这里从创建虚拟机开始记录. 选择创建虚拟机 下一步 选择稍后安装 选择安装的操作系统版本,需要说明的是,CentOs 5 就是RHEL 5 设置虚拟机名称及虚拟机位置 ...

  6. [学习笔记] Web设计过程中该做和不该做的

    原文网址: http://www.javascriptstyle.com/the-dos-and-donts-of-web-design -该做的: QR代码QR代码即快速响应代码,这是矩阵条形码的一 ...

  7. CDH版HDFS Block Balancer方法

    命令: sudo -u hdfs hdfs balancer 默认会检查每个datanode的磁盘使用情况,对磁盘使用超过整个集群10%的datanode移动block到其他datanode达到均衡作 ...

  8. ZOJ3772 - Calculate the Function(线段树+矩阵)

    题目大意 给定一个序列A1 A2 .. AN 和M个查询 每个查询含有两个数 Li 和Ri. 查询定义了一个函数 Fi(x) 在区间 [Li, Ri] ∈ Z. Fi(Li) = ALi Fi(Li ...

  9. Unity3D-数学相关

    1. Transform.rotation:对象在世界坐标系下的旋转:Transform.localRotation:对象在父对象的局部坐标系下的旋转.两个变量的类型均为四元素. (1)得到游戏对象当 ...

  10. Failed to allocate the network(s), not rescheduling

    Failed to allocate the network(s), not rescheduling 在计算节点的/etc/nova/nova.conf中添加下面两句 #Fail instance ...