js-函数式编程-monad-容器交互-解嵌套

同步和异步的例子:

import fs from 'fs'
import path from 'path'
import * as R from 'ramda'
const trace = R.curry((label, v) => {
  console.log(label, v)
  return v
})
const Maybe = function(x) {
  this.__value = x
}

Maybe.of = function(x) {
  return new Maybe(x);
}

Maybe.prototype.isNothing = function() {
  return (this.__value === null) || (this.__value === undefined);
}

Maybe.prototype.map = function(fun) {
  return this.isNothing() ? Maybe.of(null) : Maybe.of(fun(this.__value));
}

var map = R.curry(function(f, any_functor_at_all) {
  return any_functor_at_all.map(f);
});

let r = Maybe.of(1336).map(R.add(1))
console.log(r) // Maybe { __value: 1337 }

let addFn = x => Maybe.of(R.add(1, x))

let rr = Maybe.of(1336).map(addFn)
console.log(rr) // Maybe { __value: Maybe { __value: 1337 } }



var IO = function(f) {
  this.__value = f;
}

IO.of = function(x) {
  return new IO(function() {
    return x;
  });
}

IO.prototype.isNothing = function() {
  return (this.__value === null) || (this.__value === undefined);
}

IO.prototype.map = function(f) {
  return new IO(R.compose(f, this.__value));
}

// 异步
// Support
// ===========================
// var fs = require('fs');
//  readFile :: String -> IO String
var readFile = function(filename) {
  return new IO(function() {
    return fs.readFileSync(filename, 'utf-8')
  });
};

//  print :: String -> IO String
var print = function(x) {
  return new IO(function() {
    // console.log(x);
    return x;
  });
}

// Example
// ===========================
//  cat :: IO (IO String)
var cat = R.compose(
  // map(print), // map(print) == print
  print, // 优化
  readFile
)
let filePath = path.join("./config.json") 
let file = cat(filePath)
console.log(file.__value().__value())

IO.prototype.join = function() {
  return this.isNothing() ? IO.of(null): this.__value()
}
const join = function(mma) {
  return mma.join()
}
// Example
// ===========================
//  cat :: IO (IO String)
var cat2 = R.compose(
  join,
  join,
  // map(print), // map(print) == print
  print, // 优化
  readFile
)
console.log(cat2(filePath))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值