[Functional Programming] Function modelling -- 4. Reader Monda example

[亡魂溺海] 提交于 2020-03-14 06:30:59
const Reader = run => ({
  run,
  map: f => Reader(x => f(run(x))),
  chain: f => Reader(x => f(run(x)).run(x)),
  concat(o) {
    return Reader(x => run(x).concat(o.run(x)));
  }
});
Reader.of = x => Reader(() => x);
Reader.ask = Reader(x => x);

const prefix = s => m => `${s}${m}`;
const prefixHttps = prefix("https://");
const prefixHttp = prefix("http://");

const res = Reader.of("localhost")
  .chain(host =>
    Reader.ask.map(config =>
      config.https ? prefixHttps(host) : prefixHttp(host)
    )
  )
  .chain(domain =>
    Reader.ask.map(config => `${domain.concat(":").concat(config.port)}`)
  )
  .run({ port: 3000, https: true });

console.log(res); // https://localhost:3000

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!