zoukankan      html  css  js  c++  java
  • [Functional Programming] Async IO Functor

    We will see a peculiar example of a pure function. This function contained a side-effect, but we dubbed it pure by wrapping its action in another function. Here's another example of this:

    // getFromStorage :: String -> (_ -> String)
    const getFromStorage = key => () => localStorage[key];

    'localStorage' is a side effect, but we wrap into a function call, so what 'getFromStorage' return is not a value but a function. And this returned function is waiting to be called, before calling, we can do all kind of function mapping of composion on it, that's the beautity.

    Let's see how to define a IO functor for this side-effect code:

    class IO {
      static of(x) {
        return new IO(() => x);
      }
    
      constructor(fn) {
        this.$value = fn;
      }
    
      map(fn) {
        return new IO(compose(fn, this.$value));
      }
    
      inspect() {
        return `IO(${this.$value})`;
      }
    }

    IO will take a function as input. 

    Example of IO:

    ( Note: the reuslt shown in comment is not actual result, the actual result is wrapped in {$value: [Function]}, just for now, we show the result which should be in the end.)

    // ioWindow :: IO Window
    const ioWindow = new IO(() => window);
    
    ioWindow.map(win => win.innerWidth);
    // IO(1430)
    
    ioWindow
      .map(prop('location'))
      .map(prop('href'))
      .map(split('/'));
    // IO(['http:', '', 'localhost:8000', 'blog', 'posts'])

    There is some library already define the IO functor for us, we don't need to write one for our own, for example, Async from Crocks.js, or Data.Task from Folktale.

    Here we are using 'Data.Task' as an example:

    // -- Node readFile example ------------------------------------------
    
    const fs = require('fs');
    
    // readFile :: String -> Task Error String
    const readFile = filename => new Task((reject, result) => {
      fs.readFile(filename, (err, data) => (err ? reject(err) : result(data)));
    });
    
    readFile('metamorphosis').map(split('
    ')).map(head);
    // Task('One morning, as Gregor Samsa was waking up from anxious dreams, he discovered that
    // in bed he had been changed into a monstrous verminous bug.')
    
    
    // -- jQuery getJSON example -----------------------------------------
    
    // getJSON :: String -> {} -> Task Error JSON
    const getJSON = curry((url, params) => new Task((reject, result) => {
      $.getJSON(url, params, result).fail(reject);
    }));
    
    getJSON('/video', { id: 10 }).map(prop('title'));
    // Task('Family Matters ep 15')
    
    
    // -- Default Minimal Context ----------------------------------------
    
    // We can put normal, non futuristic values inside as well
    Task.of(3).map(three => three + 1);
    // Task(4)

    To run the Task, we need to call 'fork(rej, res)':

    // -- Pure application -------------------------------------------------
    // blogPage :: Posts -> HTML
    const blogPage = Handlebars.compile(blogTemplate);
    
    // renderPage :: Posts -> HTML
    const renderPage = compose(blogPage, sortBy(prop('date')));
    
    // blog :: Params -> Task Error HTML
    const blog = compose(map(renderPage), getJSON('/posts'));
    
    
    // -- Impure calling code ----------------------------------------------
    blog({}).fork(
      error => $('#error').html(error.message),
      page => $('#main').html(page),
    );

    Example of Either & IO:

    // validateUser :: (User -> Either String ()) -> User -> Either String User
    const validateUser = curry((validate, user) => validate(user).map(_ => user));
    
    // save :: User -> IO User
    const save = user => new IO(() => ({ ...user, saved: true }));
    
    const validateName = ({ name }) => (name.length > 3
      ? Either.of(null)
      : left('Your name need to be > 3')
    );
    
    const saveAndWelcome = compose(map(showWelcome), save);
    
    const register = compose(
      either(IO.of, saveAndWelcome),
      validateUser(validateName),
    );

    More detail

  • 相关阅读:
    js定时相关函数:
    远程控制使用kill软件映射内网进行远程控制(9.28 第十四天)
    PHP基础(9.27 第十三天)
    使用kali中的Metasploit通过windows7的永恒之蓝漏洞攻击并控制win7系统(9.27 第十三天)
    Nmap目录扫描和漏洞扫描(9.27 第十三天)
    JS正则和点击劫持代码(第十二天 9.27)
    Banner信息收集和美杜莎使用(9.26 第十二天)
    JavaScript的运算符、条件判断、循环、类型转换(9.25 第十一天)
    使用BurpSuite和Hydra爆破相关的服务(9.25 第十一天)
    JavaScript(第十一天 9.24)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10423861.html
Copyright © 2011-2022 走看看