[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 ...
随机推荐
- Java常用工具类之时间转换(注释乱码,全)
package com.wazn.learn.util; import java.text.ParseException; import java.text.SimpleDateFormat; imp ...
- aop相关术语
AOP是OOP的延续,是Aspect Oriented Programming的缩写,意思是面向切面的编程.并不是全部的AOP框架都是一样的.他们连接点模型的功能可能有强弱之分,有些可以字段,方法,构 ...
- 【BZOJ 2728】 2728: [HNOI2012]与非 (线性基?)
2728: [HNOI2012]与非 Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 813 Solved: 389 Description Inpu ...
- 【hash】BZOJ3751-[NOIP2014]解方程
[题目大意] 已知多项式方程:a0+a1*x+a2*x^2+...+an*x^n=0.求这个方程在[1,m]内的整数解(n和m均为正整数). [思路] *当年考场上怒打300+行高精度,然而没骗到多少 ...
- bzoj 2770 堆的中序遍历性质
我们知道二叉搜索树的中序遍历是一个已经排好序的序列,知道序列我们无法确定树的形态(因为有多种). 但是,Treap如果告诉我们它的关键字以及权值,那么就可以唯一确定树的形态(Treap的O(logn) ...
- 通过wifi上网,桥接模式下virtualBox虚拟机无法连上网的解决办法
https://jingyan.baidu.com/article/948f59242e601dd80ff5f929.html
- CodeM资格赛5
早上起床太晚,最后没时间了.. 不是ac代码,下次题目在oj上线的时候再去做一下.. #include<iostream> #include<cstdio> #include& ...
- SQL Server 2008 Windows身份验证改为混合模式身份验证 及修改sa密码
由于需要,要把SQL2008单一的Windows身份验证改为混合模式身份验证.在此做一备忘. 步骤: 1.用Windows身份验证方式进入SQL2008,在[对象资源管理器]右键击[根目录]:
- Mastering stack and heap for system reliability
http://www.iar.com/Global/Resources/Developers_Toolbox/Building_and_debugging/Mastering_stack_and_he ...
- visual studio 2008试用版的评估期(万能破解)
教程 http://jingyan.baidu.com/article/a3a3f811ee87268da2eb8ae7.html 参考: http://blog.chinaunix.net/uid- ...