[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 ...
- TCP/IP——ARP与RARP简记
ARP(Address Resolution Protocol):ARP为IP地址到对应的硬件地址(MAC)之间提供动态映射.这个过程是自动完成的,一般应用程序用户和系统管理员不必要关心. ARP高速 ...
- Vue.js 系列教程 3:Vue
原文:intro-to-vue-3-vue-cli-lifecycle-hooks 译者:nzbin 这是 JavaScript 框架 Vue.js 五篇教程的第三部分.在这一部分,我们将学习 Vue ...
- Nginx服务器的启动控制
写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------主要内容包括: nginx服 ...
- [转]Android网格视图(GridView)
GridView的一些属性: 1.android:numColumns=”auto_fit” //GridView的列数设置为自动,也可以设置成2.3.4…… 2.android:columnWi ...
- iOS 发光字流水
{ CAGradientLayer *_gradientLayer; NSInteger count; } - (void)addLabel{ // 创建UILabel UILabel *label ...
- VMware中网络设置之NAT
当完成VMwareWorkStation安装之后,网络连接中会多出两个网络连接,分别是VMnet1和VMnet8,如下图所示: 整个机器的结构就可以抽象成:VMware虚拟机系统(虚拟网卡vmnet0 ...
- 转:IntelliJ IDEA 2016.1.3注册破解激活
IntelliJ IDEA 2016.1.3下载地址 https://download.jetbrains.8686c.com/idea/ideaIU-2016.1.3.exe 用注册码激活: 激活码 ...
- 解决新版本webpack vue-cli生成文件没有dev.server.js问题
新版本webpack生成的dev.server.js 在webpack.dev.conf.js中 webpack.dev.conf.js const axios = require('axios') ...
- flex弹性盒子
注意事项 1.设为Flex布局之后,子元素的float,clear和vertical-align属性都讲失效 2.采用Flex布局的元素,称为Flex容器(Flex container),所有的子元素 ...