函数式编程-函子(3)

2021-07-31  本文已影响0人  Fantast_d2be

Functor(函子)

函数式程序即通过管道把数据在一系列的纯函数间传递的程序。但是对于异常处理,异步操作,副作用如何处理?这个时候就需要容器即函子。

什么是Functor

Functor函子

class Container {
  static of (value) {
    return new Container(value)
  }
  
  constructor (value) {
    this._value = value
  }
  
  map (fn) {
    return Container.of(fn(this._value))
  }
}

Container.of(3)
    .map(x => x + 2)
    .map(x => x * x)

MayBe函子

Container.of(null).map(x => x.toUpperCase())
class MayBe {
    static of(value) {
        return new MayBe(value);
    }
    constructor(value) {
        this._value = value;
    }
    map(fn) {
        return this.isNothing()
            ? MayBe.of(this._value)
            : MayBe.of(fn(this._value));
    }
    isNothing() {
        return this._value === null || this._value === undefined;
    }
}
console.log(MayBe.of("Hello world").map((x) => x.toUpperCase()));
console.log(MayBe.of(undefined).map((x) => x.toUpperCase()));
MayBe.of("hello world")
    .map((x) => x.toUpperCase())
    .map((x) => null)
    .map((x) => x.split(" "));

Either函子

class Left {
    static of(value) {
        return new Left(value);
    }
    constructor(value) {
        this._value = value;
    }
    map(fn) {
        return Left.of(this._value);
    }
}

class Right {
    static of(value) {
        return new Right(value);
    }
    constructor(value) {
        this._value = value;
    }
    map(fn) {
        return Right.of(fn(this._value));
    }
}
function parseJSON(json) {
    try {
        return Right.of(JSON.parse(json));
    } catch (e) {
        return Left.of({ error: e.message });
    }
}

let r = parseJSON('{"name": "zs"}').map((x) => x.name.toUpperCase());
console.log(r);

IO函子

const fp = require("lodash/fp");
class IO {
    static of(x) {
        return new IO(function () {
            return x;
        });
    }
    constructor(fn) {
        this._value = fn;
    }
    map(fn) {
        return new IO(fp.flowRight(fn, this._value));
    }
}
let io = IO.of(process)
    .map((p) => p.execPath)
    .map((p) => p.toUpperCase());
console.log(io._value());

异步函子

const { task } = require("folktale/concurrency/task");

var fs = require("fs");

var readFile = function (filename) {
    return new task(function ({ reject, resolve }) {
        fs.readFile(filename, "utf-8", function (err, data) {
            err ? reject(err) : resolve(data);
        });
    });
};

readFile("./package.json")
    .map((data) => data.toUpperCase())
    .run()
    .listen({
        onCancelled: () => {
            console.log("the task was cancelled");
        },
        onRejected: (error) => {
            console.log("something went wrong");
        },
        onResolved: (value) => {
            console.log(value);
        },
    });

Pointed函子

class Container {
  static of(value) {
    return new Container(value)
  }
  map() {
    ...
  }
}

Contanier.of(2).map(...)
上一篇下一篇

猜你喜欢

热点阅读