pointed functor
最后更新于:2022-04-02 04:18:09
[TOC]
## pointed functor
- *pointed functor*是实现了`of`方法的 functor(详情查看第八章)
bad
```
// 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 = compose(map(print), readFile);
cat(".git/config")
// IO(IO("[core]\nrepositoryformatversion = 0\n"))
```
我们得到的是一个`IO`,只不过它陷进了另一个`IO`
good
```
var mmo = Maybe.of(Maybe.of("nunchucks"));
// Maybe(Maybe("nunchucks"))
mmo.join();
// Maybe("nunchucks")
var ioio = IO.of(IO.of("pizza"));
// IO(IO("pizza"))
ioio.join()
// IO("pizza")
var ttt = Task.of(Task.of(Task.of("sewers")));
// Task(Task(Task("sewers")));
ttt.join()
// Task(Task("sewers"))
```
如果有两层相同类型的嵌套,那么就可以用`join`把它们压扁到一块去
### 一个 join
一个 functor,只要它定义个了一个`join`方法和一个`of`方法,并遵守一些定律,那么它就是一个 monad
```
Maybe.prototype.join = function() {
return this.isNothing() ? Maybe.of(null) : this.__value;
}
```
实例
```
// log :: a -> IO a
var log = function(x) {
return new IO(function() { console.log(x); return x; });
}
// setStyle :: Selector -> CSSProps -> IO DOM
var setStyle = curry(function(sel, props) {
return new IO(function() { return jQuery(sel).css(props); });
});
// getItem :: String -> IO String
var getItem = function(key) {
return new IO(function() { return localStorage.getItem(key); });
};
// applyPreferences :: String -> IO DOM
var applyPreferences = compose(
join, map(setStyle('#main')), join, map(log), map(JSON.parse), getItem
);
applyPreferences('preferences').unsafePerformIO();
// Object {backgroundColor: "green"}
//
```
';