zoukankan      html  css  js  c++  java
  • [Compose] Isomorphisms and round trip data transformations

    What is Isomorphisms?
    We have a value x, then apply function 'to' and 'from' to value 'x', the result we should still get 'x'.

    // from(to(x)) == x
    // to(from(y)) == y

    So Isomorphisms is kind of opreation able to tranform a value back and forward without lose anything.

    Example1:

    const Iso = (to, from) => ({
      to,
      from
    }) 
    
    // String <-> [Chat]
    const StoC = Iso(
      (str) => str.split(''),
      (chat) => chat.join('')
    );
    
    const res = StoC.from(StoC.to('How'));

    Example2: 

    // String <-> [Chat]
    const StoC = Iso(
      (str) => str.split(''),
      (chat) => chat.join('')
    );
    
    const truncate = (str, num) => StoC.from(StoC.to(str).slice(0,num)).concat('...');
    let res = truncate("Hello World!", 7);
    console.log(res); // "Hello W..."

    Example3:

    const Iso = (to, from) => ({
      to,
      from
    }) 
    
    // [a] <-> Either/null/a
    const singleton = Iso(
      (either) => either.fold(() => [], x => [x]),
      ([x]) => x? Right(x): Left()
    )
    
    const filterEither = (e, pred) => singleton.from(singleton.to(e).filter(pred));
    const res = filterEither(Right('hello'), (x) => x.match(/h/ig))
                    .map(x => x.toUpperCase());
  • 相关阅读:
    PHP 对Memcache的使用实例
    PHP Memcache 扩展安装
    Effective STL 读书笔记
    windows下安装和使用scrapy
    使用insert ignore来避免向数据库重复插入数据
    2017年末
    归并排序
    二叉树的中序遍历
    正则表达式
    tinymq学习小结
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6344185.html
Copyright © 2011-2022 走看看