4 ms·
you can do this in c++ as well with a lambda const value = [&]() { if (a) { return true; } return switch (b) { case 1: return fals
by deathvyp3r 4y ago
you can do this in c++ as well with a lambda
const value = [&]() {
if (a) {
return true;
}
return switch (b) {
case 1: return false;
default: return undefinied;
}
}();
- andix 4y agoSure, in a lot of languages this is possible, but usually much slower, even slower than named functions. Can the c++ compiler in-line the lambda and remove the function call completely? Still the syntax is a bit confusing. In ML languages (f# and also rust are somehow descendants of ML) you can just use if .. else if .. else expressions. They work like ternaries! But easier readable. Nested ternaries are useful, but get really hard to read very fast. (x = condition1 ? A : condition2 ? B : C;)
- monocasa 4y ago> Can the c++ compiler in-line the lambda and remove the function call completely? LLVM and GCC can at least.
- somewhereoutth 4y agoAnd indeed almost exactly like that in JavaScript - just substitute ()=> for the [&]()
- wruza 4y agoYou can’t directly call a function definition in js, so it will look like this: const value = (()=>{ … })()
- tialaramex 4y agoAn immediately invoked lambda pattern, but, check out how ugly that was compared to: let value = if a { true } else { match b { 1 => false, _ => undefined } }; And notice that because now we're a function our relationship to the world changed, how does your immediately invoked lambda do this? let value = if a { true } else { match b { 1 => false, 2 => return foo, _ => undefined }}; With expression syntax returning from the function we're in is fine† but in your lambda you can't do that, you need control flow logic outside the lambda to handle it. † You might wonder about the inferred type of this expression since it might return. The type of the return expression in Rust is ! aka Never, which is an empty type. In the same way that N + 0 == N in integer arithmetic, any type plus an empty type is the original type again in type arithmetic, so the type of the expression isn't altered.