zl程序教程

您现在的位置是:首页 >  其它

当前栏目

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

-- Function Programming Example functional Reader
2023-09-14 09:00:47 时间
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