我正在尝试功能List
类型和结构共享。由于Javascript没有Tail Recursive Modulo Cons优化,我们不能像这样编写List
个组合器,因为它们不是堆栈安全的:
const list =
[1, [2, [3, [4, [5, []]]]]];
const take = n => ([head, tail]) =>
n === 0 ? []
: head === undefined ? []
: [head, take(n - 1) (tail)];
console.log(
take(3) (list) // [1, [2, [3, []]]]
);

现在我尝试递归地实现take
尾部,这样我就可以依赖TCO(在Ecmascript中仍然是一个未解决的Promise
)或使用蹦床(在示例中省略以保持简单) :
const list =
[1, [2, [3, [4, [5, []]]]]];
const safeTake = n => list => {
const aux = (n, acc, [head, tail]) => n === 0 ? acc
: head === undefined ? acc
: aux(n - 1, [head, acc], tail);
return aux(n, [], list);
};
console.log(
safeTake(3) (list) // [3, [2, [1, []]]]
);

这有效但新创建的列表的顺序相反。如何以纯粹的功能性方式解决这个问题?
答案 0 :(得分:2)
防止列表反转的一种方法是使用延续传递样式。现在就把它放在你选择的蹦床上......
const None =
Symbol ()
const identity = x =>
x
const safeTake = (n, [ head = None, tail ], cont = identity) =>
head === None || n === 0
? cont ([])
: safeTake (n - 1, tail, answer => cont ([ head, answer ]))
const list =
[ 1, [ 2, [ 3, [ 4, [ 5, [] ] ] ] ] ]
console.log (safeTake (3, list))
// [ 1, [ 2, [ 3, [] ] ] ]

这是在蹦床上
const None =
Symbol ()
const identity = x =>
x
const call = (f, ...values) =>
({ tag: call, f, values })
const trampoline = acc =>
{
while (acc && acc.tag === call)
acc = acc.f (...acc.values)
return acc
}
const safeTake = (n = 0, xs = []) =>
{
const aux = (n, [ head = None, tail ], cont) =>
head === None || n === 0
? call (cont, [])
: call (aux, n - 1, tail, answer =>
call (cont, [ head, answer ]))
return trampoline (aux (n, xs, identity))
}
const list =
[ 1, [ 2, [ 3, [ 4, [ 5, [] ] ] ] ] ]
console.log (safeTake (3, list))
// [ 1, [ 2, [ 3, [] ] ] ]
答案 1 :(得分:2)
Laziness免费为您提供尾递归模数。因此,显而易见的解决方案是使用thunk。但是,我们不只是想要任何一种thunk。我们想要weak head normal form中的表达式。在JavaScript中,我们可以使用lazy getters实现此目的,如下所示:
const cons = (head, tail) => ({ head, tail });
const list = cons(1, cons(2, cons(3, cons(4, cons(5, null)))));
const take = n => n === 0 ? xs => null : xs => xs && {
head: xs.head,
get tail() {
delete this.tail;
return this.tail = take(n - 1)(xs.tail);
}
};
console.log(take(3)(list));
使用懒惰的getter有很多好处:
希望有所帮助。