F# is an expression-oriented language so, as Karl Bielefeldt points out, having if/else
expressions that don't actually return any value is unidiomatic already.
Another aspect of idiomatic functional code is to make it explicit that all possible branches are being addressed.
That's one of the reasons why pattern matching with discriminated unions is so popular -- the compiler will warn you if you have forgotten a case.
The if/else
by itself is perfectly acceptable, but it sounds like you are doing something a bit more complicated, when you have complex conditions like this.
If I was looking at this code, I would ask what happens if not conditionA
holds? The code does not make that clear.
If this set of nested conditions occurs frequently, or is a critical piece of code that requires clarity, then I personally would replace the various conditions with a discriminated union to make it obvious to the reader what is going on.
type Keypress =
| AOnly
| AAndB
| NeitherANorB
(Obviously, the names are ugly -- you should rename the cases according to your needs!)
Then create a translator function that turns the input into one of the Keypress
cases:
let inputToKeypress input =
if conditionA then
if conditionB then AAndB else AOnly
else
NeitherANorB
Finally, your main code can pattern match in an obvious way.
let mainCode keypress =
match keypress with
| AOnly -> do something
| AAndB -> do something; do something more;
| NeitherANorB -> () // ignore
An additional advantage of this approach is that if you add or remove cases in your union type, your code will fail to compile. Not so with nested if
expressions.
let foo = if (blah) then "A" else "B"
is valid. What's less idiomatic is using impure, side-effecting functions in your code. That's going to be impure regardless of whether or not you're using If-statements though (and sometimes it can't be avoided, so don't sweat it). – KChaloux Jan 08 '15 at 22:41