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),
);

More detail

[Functional Programming] Async IO Functor的更多相关文章

  1. Functional Programming without Lambda - Part 2 Lifting, Functor, Monad

    Lifting Now, let's review map from another perspective. map :: (T -> R) -> [T] -> [R] accep ...

  2. Beginning Scala study note(4) Functional Programming in Scala

    1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...

  3. Async IO

    I was recently reading a series on “Write Sequential Non-Blocking IO Code With Fibers in NodeJS” by  ...

  4. 关于函数式编程(Functional Programming)

    初学函数式编程,相信很多程序员兄弟们对于这个名字熟悉又陌生.函数,对于程序员来说并不陌生,编程对于程序员来说也并不陌生,但是函数式编程语言(Functional Programming languag ...

  5. [Functional Programming] Function signature

    It is really important to understand function signature in functional programming. The the code exam ...

  6. JavaScript Functional Programming

    JavaScript Functional Programming JavaScript 函数式编程 anonymous function https://en.wikipedia.org/wiki/ ...

  7. 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 ...

  8. 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 ...

  9. Functional programming

    In computer science, functional programming is a programming paradigm, a style of building the struc ...

随机推荐

  1. zabbix api 设置维护模式

    通过zabbix提供的api进行维护模式的设置 #!/usr/bin/env python # -*-coding:utf-8-*- import urllib import urllib2 impo ...

  2. 我对于react-router路由原理的学习

    目录 react-router依赖基础--history react-router是如何实现URL与UI同步 一 react-router依赖基础--history history是一个独立的第三方j ...

  3. 51nod1805 小树 prufer序列 + 容斥原理

    首先考虑$prufer$序列,那么问题转化为求 一个长为$n - 2$的序列,总共有$n$个元素,恰有$m$个元素不出现在序列中的方案数 考虑容斥,答案即为 至少$m$个元素不出现 - 至少$m + ...

  4. 51nod1819 黑白树V2

    简单的题面 给定一棵以1为根的有根树,点可能是黑色或白色,操作如下. 1. 选定一个点x,将x的子树中所有到x的距离为奇数的点的颜色反转.2. 选定一个点x,将点x的颜色反转.3. 选定一个点x,询问 ...

  5. 三、python的数据类型 列表、元组、字典

    1.list 列表 列表是由一序列特定顺序排列的元素组成的.可以把字符串,数字,字典等都可以任何东西加入到列表中,列表中的元素之间没有任何关系.列表也是自带下标的,默认也还是从0开始. List常用的 ...

  6. Codeforces Beta Round #92 (Div. 1 Only) A. Prime Permutation 暴力

    A. Prime Permutation 题目连接: http://www.codeforces.com/contest/123/problem/A Description You are given ...

  7. Read UNIQUE ID and flash size method for stm32

    /* 读取stm32的unique id 与 flash size */ /* func: unsigned int Read_UniqueID_Byte(unsigned char offset) ...

  8. mysql 实验

    http://yangyaru0108.blog.51cto.com/6616699/1205001

  9. ORACLE FORMS PL/SQL PACKAGE SHOW TIPS WINDOW

    --在开发ORACLE FORM的程序中,要编写PL/SQL程序包产出异常情况时,直接在FORM弹出一个异常提示窗口 DECLARE BEGIN app_exception.raise_excepti ...

  10. 【spring boot】整合LCN,启动spring boot2.0.3 启动报错:Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.

    spring boot 2.0.3启动报错: Error starting ApplicationContext. To display the conditions report re-run yo ...