4 ms·
In theory you could create a language without if/else as long as it has pattern matching, because if/else can be emulated like so: match condition {
by armchairhacker 4y ago
In theory you could create a language without if/else as long as it has pattern matching, because if/else can be emulated like so:
match condition {
true => { ... }
false => { ... }
}
In fact you can create a language without if/else and pattern-matching, if you have something like first-class functions to handle branching. One notable example of such a language is lambda-calculus:
true = λtf.t
false = λtf.f
if = λctf.ctf
Which in more familiar syntax is
true = (t, f) => t()
false = (t, f) => f()
if = (c, t, f) => c(t, f)
And would evaluate like so
if(true, workCorrectly, crashAndBurn)
==> true(workCorrectly)
==> workCorrectly()
However in practice, most high-level languages have if/else. Even lesser-known functional languages like Coq and Haskell which rely more on their pattern matching, still include it simply because it's convenient and easy to implement. Worst case, the compiler can (and sometimes does) just desugar the conditional into one of the above.
- Measter 4y agoI hate that (nightly) Rust lets you do this: #![feature(fn_traits)] #![feature(unboxed_closures)] struct If; impl<T, F, V> FnOnce<(bool, T, F)> for If where T: FnMut() -> V, F: FnMut() -> V { type Output = V; extern "rust-call" fn call_once(self, args: (bool, T, F)) -> Self::Output { let (condition, mut yay, mut nay) = args; let arms: [&mut dyn FnMut() -> V; 2] = [&mut nay, &mut yay]; arms[condition as usize]() } } https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=1b8101ffae222b9645d28a570d0cd72c https://play.rust-lang.org/?version=nightly&mode=release&edi...
- db48x 4y agoWhy do you hate that Rust allows you to write this? You could write something like this in most modern languages.
- tluyben2 4y agoYou would want to find a high level language for which adding if/then would add expressiveness as defined here [0]. If it does not add expressiveness, it’s just desugaring/macros, which is basically the same as having if/then in the first place. [0] https://jgbm.github.io/eecs762f19/papers/felleisen.pdf https://jgbm.github.io/eecs762f19/papers/felleisen.pdf