同步和异步的例子:
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))