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. fastdb中的位图应用

    位图内存管理: 每块内存用一个二进制位表示它的使用状态,如果该块内存被占用,则把对应位图中的对应位置1,如果空闲则置0,原理十分简单.计算机里面处理的位数最少的变量是字节(byte),所以也就是8位做 ...

  2. [Everyday Mathematics]20150120

    设 $f:\bbR\to\bbR$ 二阶可微, 且 $$\bex f(0)=2,\quad f'(0)=-2,\quad f(1)=1. \eex$$ 试证: $$\bex \exists\ \xi\ ...

  3. Dev gridControl 添加表标题

    1.OptionsView ->ShowViewCaption = True 2.ViewCaption = "标题"

  4. hdu 2087-剪花布条(KMP)

    题意: 求文本串最多可以分成几个模式串. 分析: KMP #include <map> #include <set> #include <list> #includ ...

  5. 关于java异常的一点思考

    关于异常的一点思考 异常生命周期 异常的来源 所有的异常都是抛出来的 有底层api抛出的 有自定义抛出的 异常的处理 1, 运行时异常 不做任何处理仍可编译通过 不建议捕获(不建议用异常来做流程控制, ...

  6. MVC & MVVM

    什么是MVC,什么是MVVM? 面向过程 --> 面向对象 --> MVC --> MV* 面向过程: 开发人员按照需求逻辑顺序开发代码逻辑,主要思维模式在于如何实现.先细节,后整体 ...

  7. 微软控制台带来的PHP控制台输出问题

    /** * 测试文件包含方式对跨平台的影响 * 控制台下测试. * 默认的文件编码为 UTF-8 */ function testChinese() { $file = __DIR__ . '/con ...

  8. 【SummaryPlan】Summary of Feb & Plan of March——How to 'just do it'?

    Why I choose to be a graduate student from an undergraduate student? It’s time to applying for inter ...

  9. 结合Vim ghostscript 将源代码文件转换成语法高亮的pdf格式文档

    step 1: 安装ghostscript (debian 环境, 其他环境自行google) sudo apt-get install ghostscript step 2:  用Vim生成ps文件 ...

  10. Lucene Query Term Weighting

    方法 public static Query TermWeighting(Query tquery,Map<String,Float>term2weight){ BooleanQuery ...