[Javascript] Monads
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的更多相关文章
- 翻译连载 |《你不知道的JS》姊妹篇 |《JavaScript 轻量级函数式编程》- 引言&前言
原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 译者团队(排名不分先后):阿希.blueken.brucec ...
- JavaScript 风格指南
来源于: https://github.com/alivebao/clean-code-js 目录 介绍 变量 函数 对象和数据结构 类 测试 并发 错误处理 格式化 注释 介绍 作者根据 Rober ...
- 给 JavaScript 开发者讲讲函数式编程
本文译自:Functional Programming for JavaScript People 和大多数人一样,我在几个月前听到了很多关于函数式编程的东西,不过并没有更深入的了解.于我而言,可能只 ...
- 一文带你了解JavaScript函数式编程
摘要: 函数式编程入门. 作者:浪里行舟 Fundebug经授权转载,版权归原作者所有. 前言 函数式编程在前端已经成为了一个非常热门的话题.在最近几年里,我们看到非常多的应用程序代码库里大量使用着函 ...
- Clean Code of JavaScript
Clean Code of JavaScript 代码简洁之道 JavaScript 版 https://github.com/ryanmcdermott/clean-code-javascript ...
- 前端大牛带你了解JavaScript 函数式编程
前言 函数式编程在前端已经成为了一个非常热门的话题.在最近几年里,我们看到非常多的应用程序代码库里大量使用着函数式编程思想. 本文将略去那些晦涩难懂的概念介绍,重点展示在 JavaScript 中到底 ...
- JavaScript之父Brendan Eich,Clojure 创建者Rich Hickey,Python创建者Van Rossum等编程大牛对程序员的职业建议
软件开发是现时很火的职业.据美国劳动局发布的一项统计数据显示,从2014年至2024年,美国就业市场对开发人员的需求量将增长17%,而这个增长率比起所有职业的平均需求量高出了7%.很多人年轻人会选择编 ...
- javascript中的Array对象 —— 数组的合并、转换、迭代、排序、堆栈
Array 是javascript中经常用到的数据类型.javascript 的数组其他语言中数组的最大的区别是其每个数组项都可以保存任何类型的数据.本文主要讨论javascript中数组的声明.转换 ...
- Javascript 的执行环境(execution context)和作用域(scope)及垃圾回收
执行环境有全局执行环境和函数执行环境之分,每次进入一个新执行环境,都会创建一个搜索变量和函数的作用域链.函数的局部环境不仅有权访问函数作用于中的变量,而且可以访问其外部环境,直到全局环境.全局执行环境 ...
随机推荐
- Linux 中直接 I/O 机制的介绍
https://www.ibm.com/developerworks/cn/linux/l-cn-directio/ 对于传统的操作系统来说,普通的 I/O 操作一般会被内核缓存,这种 I/O 被称作 ...
- [Everyday Mathematics]20150117
设 $f:\bbR^{n\times n}\to\bbR$ 适合 $$\bex f(cA+B)=cf(A)+f(B),\quad f(AB)=f(BA),\quad\forall\ c\in\bbR, ...
- Winform使用DevExpress的WaitDialogForm画面 z
使用了DevExpress的WaitDialogForm 在应用程序加载开始时新建一个线程,并将loading画面show起来,在应用程序画面弹出前将该线程终止. 代码: private DevExp ...
- IOS init initWith 等相关集中
1.initWithCoder 当一个view从nib初始化的时候,会调用这个函数. 用keyedArchiver序列化一个类的实力,后面用keyedUnArchiver拿回来的时候会调用到 ...
- 在xcode上搭建OpenGL3.x运行环境
最近开始学习OpenGL,网上的教程太散乱,于是打算照着红宝书<OpenGL编程指南(第七版)>来学习. 于是在Mac上搭建一下Demo环境.比较方便的是,OS X上已经装了OpenGL ...
- Vim小知识
在退出vim编辑的时候,强制退出是q! 感叹号在前,即!q,表示执行外部shell命令,感叹号在后,即q!,表示强制执行vi命令.
- [LeetCod] Single Number
Given an array of integers, every element appears twice except for one. Find that single one. Note:Y ...
- bzoj 1014 [JSOI2008]火星人prefix(splay+hash)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1014 [题意] 给定一个字符串,要求提供修改一个字符,插入一个字符,查询两个后缀LCP ...
- web服务器分析与设计(三)
面向对象分析与设计第二步:健壮性分析,完善对象 通过上一篇的分析,已经得到了构建系统中最重要的对象-----实体对象,它们封装着构成系统最重要的数据,实体数据是系统的生命. 但是光有实体还系统是运转不 ...
- Oracle创建用户及表空间 代码片段
create tablespace testdatalogging datafile 'D:\oracle\oradata\orcl\testdata.dbf' size 50m autoextend ...