[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)及垃圾回收
执行环境有全局执行环境和函数执行环境之分,每次进入一个新执行环境,都会创建一个搜索变量和函数的作用域链.函数的局部环境不仅有权访问函数作用于中的变量,而且可以访问其外部环境,直到全局环境.全局执行环境 ...
随机推荐
- [Everyday Mathematics]20150206
$$\bex \sen{fg}_{L^1}\leq C\sen{f}_{L^{r,\al}}\sen{g}_{L^{r',\al'}}, \eex$$ 其中 $$\bex f\in L^{r,\al} ...
- IOS block 记录
1.需要使用 @property(....,copy) 而不是其他的 2.self.request=[ASIHTTPRequest requestWithURL:[NSURL URLWithStrin ...
- Loadrunner模拟Json请求
一.loadrunner脚本创建 1.Insert - New step -选择Custom Request - web_custom_request 2.填入相应参数 3.生成脚本,并修改如下(参数 ...
- IAR编译信息分析
1.怎么设置可以查看单片的内存(消耗)使用状况? IAR的菜单栏 -->Tools -->IDE Options -->Messages -->Show build messa ...
- Oracle数据库管理之创建和删除数据库
转自:http://supportopensource.iteye.com/blog/678898 一.数据库管理概述 在完成Oracle软件安装后,DBA就应该对组织和管理数据库负责任,其主要任务是 ...
- gcc编译器基本命令和vi编辑器2
!1 os fen时 看电影 聊天.支持多核处理器 分任务 已经绝迹cpu Trobe c 分任务操作系统三大组成部分内核,命令解释器(shell外壳),文件系统2修改文件日期或(创建文件)命令:to ...
- bookhub -- 扁平化本地电子书管理与分享工具
代码 github 地址:https://github.com/JackonYang/bookhub 初稿: 1. 关键功能点 扫描本地电子书(扩展名 pdf/epub 等),将不重复的复制到特 ...
- 《Genesis-3D开源游戏引擎完整实例教程-2D射击游戏篇04:碰撞检测》
4.碰撞检测 碰撞概述: 游戏世界里,游戏对象不能做出如同在真实世界里的物理运动效果.对于大部分游戏来说,都要为其添加物理系统,让其可以模拟真实世界发生的物理运动.但是在这个打飞机游戏Demo中,是用 ...
- 优雅地对泛型List 进行深拷贝
public class People { public string Name; public int Age; public People(string name, int age) { this ...
- 新手指导:教你如何查看识别hadoop是32位还是64位
问题导读: 1.从哪些地方可以识别hadoop是32位还是64位?2.hadoop本地库在什么位置? 来源:about云 本文链接:http://www.aboutyun.com/thread-127 ...