简化函数中的if语句:能否移除嵌套if-then-else优化给定代码?
Absolutely! Let's start by unpacking what your original function is doing—this makes it easy to spot the simplification opportunity right away.
Your original function:
f x y z = if y >= 15 then (if y < 23 then x*5 else f (x+4) (y+7) z) else f(x+4) (y+7) z
What It's Actually Doing
Let's break down the logic clearly:
- If
yis between 15 (inclusive) and 23 (exclusive) → returnx*5 - For every other case (either
y < 15ORy >=23) → recursively callf (x+4) (y+7) z
Notice that the two recursive branches are identical! That's the key here—we don't need nested ifs to handle this, because we can combine the two "recurse" conditions into a single catch-all.
Simplified Versions
Option 1: Use Haskell Guards (Most Idiomatic)
Guards are perfect for this kind of conditional logic, as they make the branches explicit and avoid messy nesting:
f x y z | 15 <= y && y < 23 = x * 5 | otherwise = f (x + 4) (y + 7) z
Option 2: Single If-Then-Else (No Nested Condition)
If you prefer sticking to an if statement (though guards are more idiomatic for Haskell), you can combine the conditions into one:
f x y z = if 15 <= y && y < 23 then x * 5 else f (x + 4) (y + 7) z
Why This Works
Both versions eliminate the nested if by recognizing that the two cases where we recurse are just the inverse of the single case where we return x*5. The otherwise guard (or the else clause) covers all scenarios that don't match our target condition, which is exactly what the original nested else branches were doing.
This makes the code much easier to read at a glance—anyone looking at it can immediately see the two possible outcomes, without having to parse nested conditionals.
内容的提问来源于stack exchange,提问作者Ron Wiese

