zoukankan      html  css  js  c++  java
  • [Functional Programming] Reader with Async ADT

    ReaderT is a Monad Transformer that wraps a given Monad with a Reader. This allows the interface of a Reader that enables the composition of computations that depend on a shared environment (e -> a), but provides a way to abstract a means the Reader portion, when combining ReaderTs of the same type. All ReaderTs must provide the constructor of the target Monad that is being wrapped.

    The task we want to do is read from a "data.json" file:

    {
      "name": "App",
      "config": {
        "prod": "config.prod.json",
        "dev": "config.dev.json",
        "test": "config.test.json"
      }
    }

    According to the 'env' variable we pass in, it will pick different config file:

    config.test.json:

    {
      "port": 5200
    }

    In the end, it will output a json file combine the result.

    const { readJSON, writeJSON, fork } = require("./helper");
    const {
      Async,
      ReaderT,
      omit,
      pipeK,
      assign
    } = require("crocks");
    
    const ReaderAsync = ReaderT(Async);
    const env = {
      input: "data.json",
      output: "output.json"
    };
    
    const input = env =>
      ReaderAsync(({ input }) => readJSON(input).map(assign({ env })));
    const config = data =>
      ReaderAsync(() =>
        readJSON(data.config[data.env])
          .map(assign(data))
          .map(omit(["config"]))
      );
    const output = inputData =>
      ReaderAsync(({ output }) => writeJSON(output, inputData));
    const flow = pipeK(
      ReaderAsync.of,
      input,
      config,
      output
    );
    
    fork(flow("test").runWith(env));
    

      

    output.json file:

    {
      "port": 5200,
      "name": "App",
      "env": "test"
    }
  • 相关阅读:
    一个SQL语句实现的统计功能
    VS2005中的全角BUG(C#代码)[转]
    Observer Pattern(观察者模式)及其在C#中的实现
    我觉得VS2003中最差的地方
    上班了,有点困:(
    GPRS
    今天是郁闷的一天
    今天上午给公司老总演示了SharePoint项目的产品雏形
    介绍一下SharePoint
    SharePoint Service里面的东东真让人头疼
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10957781.html
Copyright © 2011-2022 走看看