现代C++(C++20/C++23)是否有Haskell守卫式方程的等价写法?
C++20/23中模拟Haskell守卫式方程的实现方式
现代C++并没有原生支持Haskell那样的守卫式方程语法,但我们可以通过现有特性模拟出等价且优雅的实现,完美复刻你给出的Haskell示例逻辑。
首先定义示例中需要的字符串集合:
#include <string> #include <vector> #include <utility> // 用于std::pair constexpr std::vector<std::string> units = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; constexpr std::vector<std::string> teens = { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; constexpr std::vector<std::string> tens = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
最接近守卫式的直观实现
利用C++17引入的结构化绑定解构元组(对应Haskell的元组模式匹配),配合独立的if分支模拟每个守卫条件,结构上和原Haskell代码几乎一一对应:
std::string combine2(std::pair<int, int> nums) { auto [t, u] = nums; if (t == 0) { return units[u]; } if (t == 1) { return teens[u]; } if (2 <= t && u == 0) { return tens[t - 2]; } if (2 <= t && u != 0) { return tens[t - 2] + "-" + units[u]; } // 处理无效输入的默认分支 return ""; }
这种写法完全保留了守卫式方程的分支清晰性,每个条件分支独立且逻辑明确,可读性极强,和原Haskell代码的优雅感一致。
编译期版本(C++20+)
如果需要支持编译期计算,可以用constexpr链式条件表达式实现,虽然写法稍紧凑,但同样能达到等价效果:
constexpr std::string combine2_constexpr(std::pair<int, int> nums) { auto [t, u] = nums; return t == 0 ? units[u] : t == 1 ? teens[u] : (2 <= t && u == 0) ? tens[t - 2] : (2 <= t && u != 0) ? tens[t - 2] + "-" + units[u] : ""; }
补充说明
C++23也没有新增原生的守卫式语法,但可以结合std::optional或std::expected优化错误处理逻辑,核心分支逻辑依然依赖上述的条件分支写法。
内容的提问来源于stack exchange,提问作者ezyman
相关产品推荐
相关产品推荐

