According to the docs I should implement an effect with an object.
fun interface JustEffect<A> : Effect<Just<A>> {
suspend fun <B> Just<B>.bind(): B = value
}
object effect {
operator fun <A> invoke(func: suspend JustEffect<*>.() -> A): Just<A> =
Effect.restricted(eff = { JustEffect { it } }, f = func, just = { Just(it) })
}
Run Code Online (Sandbox Code Playgroud)
This is the general guide from the tutorial. I'm curious if anyone knows why they use an object? My specific use case below for …
所以我看到的尾递归的常见例子之一是:
function factorial(x) {
if (x <= 0) {
return 1;
} else {
return x * factorial(x-1); // (A)
}
}
Run Code Online (Sandbox Code Playgroud)
它针对尾调用进行了优化:
function factorial(n) {
return facRec(n, 1);
}
function facRec(x, acc) {
if (x <= 1) {
return acc;
} else {
return facRec(x-1, x*acc); // (A)
}
}
Run Code Online (Sandbox Code Playgroud)
我明白了。但我的问题是:为什么*在这种情况下不是可以优化的功能?我不能将顶部重写为
function factorial(x) {
if (x <= 0) {
return 1;
} else {
return multiply(x, factorial(x-1)); // (A)
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这行不通。我认为这只是因为它不是真正的尾递归调用?不过,这仍然是尾部优化吗?