[Functional Programming] Async IO Functor
We will see a peculiar example of a pure function. This function contained a side-effect, but we dubbed it pure by wrapping its action in another function. Here's another example of this:
// getFromStorage :: String -> (_ -> String)
const getFromStorage = key => () => localStorage[key];
'localStorage' is a side effect, but we wrap into a function call, so what 'getFromStorage' return is not a value but a function. And this returned function is waiting to be called, before calling, we can do all kind of function mapping of composion on it, that's the beautity.
Let's see how to define a IO functor for this side-effect code:
class IO {
static of(x) {
return new IO(() => x);
}
constructor(fn) {
this.$value = fn;
}
map(fn) {
return new IO(compose(fn, this.$value));
}
inspect() {
return `IO(${this.$value})`;
}
}
IO will take a function as input.
Example of IO:
( Note: the reuslt shown in comment is not actual result, the actual result is wrapped in {$value: [Function]}, just for now, we show the result which should be in the end.)
// ioWindow :: IO Window
const ioWindow = new IO(() => window); ioWindow.map(win => win.innerWidth);
// IO(1430) ioWindow
.map(prop('location'))
.map(prop('href'))
.map(split('/'));
// IO(['http:', '', 'localhost:8000', 'blog', 'posts'])
There is some library already define the IO functor for us, we don't need to write one for our own, for example, Async from Crocks.js, or Data.Task from Folktale.
Here we are using 'Data.Task' as an example:
// -- Node readFile example ------------------------------------------
const fs = require('fs');
// readFile :: String -> Task Error String
const readFile = filename => new Task((reject, result) => {
fs.readFile(filename, (err, data) => (err ? reject(err) : result(data)));
});
readFile('metamorphosis').map(split('\n')).map(head);
// Task('One morning, as Gregor Samsa was waking up from anxious dreams, he discovered that
// in bed he had been changed into a monstrous verminous bug.')
// -- jQuery getJSON example -----------------------------------------
// getJSON :: String -> {} -> Task Error JSON
const getJSON = curry((url, params) => new Task((reject, result) => {
$.getJSON(url, params, result).fail(reject);
}));
getJSON('/video', { id: }).map(prop('title'));
// Task('Family Matters ep 15')
// -- Default Minimal Context ----------------------------------------
// We can put normal, non futuristic values inside as well
Task.of().map(three => three + );
// Task(4)
To run the Task, we need to call 'fork(rej, res)':
// -- Pure application -------------------------------------------------
// blogPage :: Posts -> HTML
const blogPage = Handlebars.compile(blogTemplate); // renderPage :: Posts -> HTML
const renderPage = compose(blogPage, sortBy(prop('date'))); // blog :: Params -> Task Error HTML
const blog = compose(map(renderPage), getJSON('/posts')); // -- Impure calling code ----------------------------------------------
blog({}).fork(
error => $('#error').html(error.message),
page => $('#main').html(page),
);
Example of Either & IO:
// validateUser :: (User -> Either String ()) -> User -> Either String User
const validateUser = curry((validate, user) => validate(user).map(_ => user)); // save :: User -> IO User
const save = user => new IO(() => ({ ...user, saved: true })); const validateName = ({ name }) => (name.length >
? Either.of(null)
: left('Your name need to be > 3')
); const saveAndWelcome = compose(map(showWelcome), save); const register = compose(
either(IO.of, saveAndWelcome),
validateUser(validateName),
);
[Functional Programming] Async IO Functor的更多相关文章
- Functional Programming without Lambda - Part 2 Lifting, Functor, Monad
Lifting Now, let's review map from another perspective. map :: (T -> R) -> [T] -> [R] accep ...
- Beginning Scala study note(4) Functional Programming in Scala
1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...
- Async IO
I was recently reading a series on “Write Sequential Non-Blocking IO Code With Fibers in NodeJS” by ...
- 关于函数式编程(Functional Programming)
初学函数式编程,相信很多程序员兄弟们对于这个名字熟悉又陌生.函数,对于程序员来说并不陌生,编程对于程序员来说也并不陌生,但是函数式编程语言(Functional Programming languag ...
- [Functional Programming] Function signature
It is really important to understand function signature in functional programming. The the code exam ...
- JavaScript Functional Programming
JavaScript Functional Programming JavaScript 函数式编程 anonymous function https://en.wikipedia.org/wiki/ ...
- Functional Programming without Lambda - Part 1 Functional Composition
Functions in Java Prior to the introduction of Lambda Expressions feature in version 8, Java had lon ...
- a primary example for Functional programming in javascript
background In pursuit of a real-world application, let’s say we need an e-commerce web applicationfo ...
- Functional programming
In computer science, functional programming is a programming paradigm, a style of building the struc ...
随机推荐
- vue 环境搭建笔记
环境 开发工具:VS Code vue版本: 2.x 准备 使用 npm 包管理器进行安装,也可以使用 yarn 包管理器. 可以使用淘宝的 npm 镜像,国内速度更快. 使用方式: $ npm in ...
- 在学习HTML——form表单中的label标签时的一点小体会
在我啃了一遍书本之后,开始了在慕课看视频的过程,从最开始的HTML+CSS的基础课程看起,在第5-9小节讲到了form表单的label标签, 首先看一下慕课的讲解: label 标签不会向用户呈现任 ...
- C和指针之学习笔记(3)
第8章 数组 1.数组与指针 数组名是一个个元素的地址. int a[10]; int b[10]; int *c; (1) c = & a[0]; &a[0]表示一个指向数 ...
- FastReport.Net使用:[11]公共对象属性介绍
公共对象属性介绍 1.Left(左),Top(上),Height(高度),Width(宽度) Left和Top,用来控制对象的位置:Height和Width用来控制对象的大小. 2.Anchor(基准 ...
- 【BZOJ 3676】 3676: [Apio2014]回文串 (SAM+Manacher+倍增)
3676: [Apio2014]回文串 Time Limit: 20 Sec Memory Limit: 128 MBSubmit: 2343 Solved: 1031 Description 考 ...
- 51nod1675 序列变换
link 题意: 给定长为n的序列a,b,下标从1开始,问有多少对x,y满足gcd(x,y)=1且$a_{b_x}=b_{a_y}$? $n\leq 10^5.$ 题解: $a_{b_x}$和$b_{ ...
- 多个Fragment在屏幕翻转会重影问题的解决
fragment使用add和hide而不用replace的方法添加到activity中,如果屏幕翻转可能会又add新的fragment进去,所以会重影. 如果有一个sparsearray保存fragm ...
- POJ 2186 Popular Cows 强连通分量模板
题意 强连通分量,找独立的块 强连通分量裸题 #include <cstdio> #include <cstdlib> #include <cstring> #in ...
- Matlab 曲线绘制之线型和颜色 示例
估计很多人会碰到,当绘制的曲线特别多的时候,需要用不同的颜色和线型区分开这些曲线.根据STC论文,自己整理了一个颜色和线型的例子,供大家直接使用,直接引用PlotStyle这个数据结构就可以了. 示例 ...
- iframe里面的页面调用父窗口,左右窗口js函数的方法
iframe里面的页面调用父窗口,左右窗口js函数的方法 实现iframe内部页面直接调用该iframe所属父窗口自定义函数的方法. 比如有A窗口,A内有个IFRAME B,B里面的装载的是C页面 ...