码迷,mamicode.com
首页 > 移动开发 > 详细

[Compose] 21. Apply Natural Transformations in everyday work

时间:2016-12-23 21:43:08      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:imm   cte   tab   mmu   res   com   for   ror   bsp   

We see three varied examples of where natural transformations come in handy.

 

const Right = x => ({
    chain    : f => f(x),
    ap       : other => other.map(x),
    traverse : (of, f) => f(x).map(Right),
    map      : f => Right(f(x)),
    fold     : (f, g) => g(x),
    concat   : o => o.fold(_ => Right(x), y => Right(x.concat(y))),
    toString : () => `Right(${x})`
});

const Left = x => ({
    chain    : f => Left(x),
    ap       : other => Left(x),
    traverse : (of, f) => of(Left(x)),
    map      : f => Left(x),
    fold     : (f, g) => f(x),
    concat   : o => o.fold(_ => Left(x), y => o),
    toString : () => `Left(${x})`
});


const fromNullable = x => x != null ?
                          Right(x) :
                          Left(null);

const Task = require(data.task);
const {List} = require(immutable-ext);

const fake = id =>
    ({
        id,
        name: user1,
        best_friend_id: id + 1
    });

const Db = ({
    find: id =>
        new Task((rej, res) => {
            res(id > 2 ? Right(fake(id)) : Left(not found))
        })
});

const eitherToTask = e =>
    e.fold(
        Task.rejected,
        Task.of
    ); // Right(x) --> Task(user)

const res = Db.find(3) // Task(Right(user))
    .chain(eitherToTask) // Task(user)
    .chain(user =>
        Db.find(user.best_friend_id)
    ) // Task(Right(user))
    .chain(eitherToTask) // Task(user)
    .fork(e => console.error(e),
          r => console.log(r)
    );

 

[Compose] 21. Apply Natural Transformations in everyday work

标签:imm   cte   tab   mmu   res   com   for   ror   bsp   

原文地址:http://www.cnblogs.com/Answer1215/p/6215862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!