Extracting data from a function chain without arrays

后端 未结 5 922
臣服心动
臣服心动 2021-01-14 01:36

This is an advanced topic of

How to store data of a functional chain of Monoidal List?

I am pretty sure we can somehow extract data from a function chain wit

5条回答
  •  攒了一身酷
    2021-01-14 01:48

    I've gone through the various questions you have but I'm still not sure I entirely understand what you're looking for. On the off chance you're simply looking to represent a linked list, here is a "dumb" representation that does not use clever tricks like overloaded arguments or default parameter values:

    const List = (() => {
      const nil = Symbol()
    
      // ADT
      const Nil = nil
      const Cons = x => xs => ({ x, xs })
      const match = ({ Nil, Cons }) => l => l === nil ? Nil : Cons(l.x)(l.xs)
    
      // Functor
      const map = f => match({
        Nil,
        Cons: x => xs => Cons(f(x))(map(f)(xs))
      })
    
      // Foldable
      const foldr = f => z => match({
        Nil: z,
        Cons: x => xs => f(x)(foldr(f)(z)(xs)) // danger of stack overflow!
                                               // https://wiki.haskell.org/Foldr_Foldl_Foldl%27
      })
    
      return { Nil, Cons, match, map, foldr }
    })()
    
    const { Nil, Cons, match, map, foldr } = List
    const toArray = foldr(x => xs => [x, ...xs])([])
    
    const l = Cons(1)(Cons(2)(Cons(3)(Nil)))
    
    const l2 = map(x => x * 2)(l)
    const l3 = map(x => x * 3)(l2)
    
    const a = toArray(l3)
    console.log(a) // => [6, 12, 18]

提交回复
热议问题