表达专门列为命令性循环的未来态

时间:2019-06-01 08:06:34

标签: javascript loops haskell recursion-schemes corecursion

我一直在尝试翻译这种专门针对List s的未来同化的Haskell递归实现

futuL :: (a -> Maybe (b, ([b], Maybe a))) -> a -> [b]
futuL f x = case f x of
  Nothing -> []
  Just (y, (ys, mz)) -> y : (ys ++ fz)
    where fz = case mz of
      Nothing -> []
      Just z -> futuL f z

进入命令式Javascript循环。这非常困难(至少对我而言):

const None = ({type: "Option", tag: "None"});
const Some = x => ({type: "Option", tag: "Some", runOption: x});

const arrFutu = coalg => x => { // futuL f x
  const acc = []; // ~ fz

  while (true) {
    let optX = coalg(x); // f x

    switch (optX.tag) { // case
      case "None": return acc; // Nothing -> []

      case "Some": {
        let [y, [ys, optX_]] = optX.runOption; // Just (y, (ys, mz))

        switch(optX_.tag) {
          case "None": {
            arrPushFlat(acc) ((ys.unshift(y), ys)); // y : (ys ++ [])
            return acc;
          }

          case "Some": { // y : (ys ++ futuL f z)
            arrPushFlat(acc) ((ys.unshift(y), ys)); 
            x = optX_.runOption;
            break;
          }

          default: throw new UnionError("invalid tag");
        }

        break;
      }

      default: throw new UnionError("invalid tag");
    }
  }
};

我很难从精神上解析Haskell代码,尤其是包含递归调用的where部分。我猜这个调用不在尾部位置,因此我的JS循环需要一个显式堆栈(acc)。

我的翻译正确吗?

1 个答案:

答案 0 :(得分:2)

由于Haskell很懒,因此可以在计算完其余部分之前开始使用“ futu”返回的列表的开头。用Java语言来讲,最好用generators来建模。

例如(为简单起见,我使用null值表示None s):

const arrFutu = coalg => function*(seed) {
    while (true) {
        const next = coalg(seed);
        if (next) {
            // Maybe (b, ([b], Maybe a)), using null for None & flattening nested tuple   
            const [item, items, nextseed] = next; 
            yield item;
            yield* items;
            // Maybe a, using null for None 
            if (nextseed) { 
                seed = nextseed;
                continue; // Continue iterating if the seed isn't null.
            }
        } 
        return;
    }
}

例如:

const coalg1 = seed => {
    if (seed < 5) {
        return ['a', ['a','a'], seed + 1];
    } else if (seed < 10) {
        return ['b', ['b','b'], seed + 1];
    } else if (seed == 10) {
        return ['c', ['c'], null];
    }
    return null;
}

for (const x of arrFutu(coalg1)(0)) {
    console.log(x);
}

for (const x of arrFutu(coalg1)(20)) {
    console.log(x);
}

最好使futu递归而不是迭代,但似乎Javascript tail call optimization doesn't work with generators


顺便说一句,即使Haskell代码不是尾部递归,递归也是"guarded":递归调用发生在一个或多个数据构造函数(此处为列表构造函数)中,并且该调用可以延迟到客户端使用返回的列表时,构造器已被客户端“剥离”。