JavaScript variable assignments from tuples

前端 未结 13 1386
[愿得一人]
[愿得一人] 2020-12-04 18:26

In other languages like Python 2 and Python 3, you can define and assign values to a tuple variable, and retrieve their values like this:

tuple = (\"Bob\", 2         


        
13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 19:15

    You can have a tuple type in Javascript as well. Just define it with higher order functions (the academic term is Church encoding):

    const Tuple = (...args) => {
      const Tuple = f => f(...args);
      return Object.freeze(Object.assign(Tuple, args));
    };
    
    const get1 = tx => tx((x, y) => x);
    
    const get2 = tx => tx((x, y) => y);
    
    const bimap = f => g => tx => tx((x, y) => Tuple(f(x), g(y)));
    
    const toArray = tx => tx((...args) => args);
    
    // aux functions
    
    const inc = x => x + 1;
    const toUpperCase = x => x.toUpperCase();
    
    // mock data
    
    const pair = Tuple(1, "a");
    
    // application
    
    console.assert(get1(pair) === 1);
    console.assert(get2(pair) === "a");
    
    const {0:x, 1:y} = pair;
    console.log(x, y); // 1 a
    
    console.log(toArray(bimap(inc) (toUpperCase) (pair))); // [2, "A"]
    
    const map = new Map([Tuple(1, "a"), Tuple(2, "b")]);
    console.log(map.get(1), map.get(2)); // a b

    Please note that Tuple isn't used as a normal constructor. The solution doesn't rely on the prototype system at all, but solely on higher order functions.

    What are the advantages of tuples over Arrays used like tuples? Church encoded tuples are immutable by design and thus prevent side effects caused by mutations. This helps to build more robust applications. Additionally, it is easier to reason about code that distinguishes between Arrays as a collection type (e.g. [a]) and tuples as related data of various types (e.g. (a, b)).

提交回复
热议问题