Reputation: 409
I would like to know if there are equivalent to Haskell guarded equations
in Modern C++
(C++20, C++23). Here is an example from Richard Bird's Haskell book where guided equations are used:
combine2 :: (Int, Int) -> String
combine2 (t, u)
| t == 0 = units!!u
| t == 1 = teens!!u
| 2 <= t && u == 0 = tens!!(t-2)
| 2 <= t && u /= 0 = tens!!(t-2) ++ "-" ++ units!!u
Is there a way of defining combine2 using guarded equations
(or equivalent to them) in C++20? (I find use of guarded equations
very beautiful!)
Upvotes: 1
Views: 114
Reputation: 52612
This looks very similar to the C or C++ ?: ternary operator, except there is no way to specify a last expression that must cover all remaining cases.
A Swift switch/case statement can specify multiple cases where the compiler must be able to confirm that one of the cases is guaranteed to be matched; the expression t >= 2 && u |= 0 may be too complex for this.
Upvotes: 0
Reputation: 7169
At the time of writing, C++ does not support anything close to that. It does not even have pattern matching which usually precedes guards in programming language development.
Note that Haskell is a declarative functional language, while C++ is not. What you call "functions" in C++ are rather to be thought as routines, or even more primitively as named chunks of code to which you can jump in and return back. Therefore it is more in the spirit of C++ to define such logic within the function's body and to some extent via virtual method dispatcher. Even Rust does not have it in function declarations (though it does have it in match
expressions).
There are some external projects which look hopeful, but I haven't looked at them in detail. For example there is this one (I'm not affiliated). Your last resort are preprocessor macros, but please don't.
Upvotes: 0