Let's say I got code like this:
if(conditionA)
do something
if(conditionA && conditionB)
do something more
Obviously, I could nest the ifs (although when there are more complicated conditions this is not readable for me) like below:
if(conditionA)
do something
if(conditionB)
do something more
How can I write similar code in f# idiomatically. I assume if statement isn't considered idiomatic in functional programming (am I wrong?)
I could write two subsequent match expressions or nested match expression to mimic above code but doing so seems pretty ugly to me.
Best Answer
There's nothing wrong with using
if-then-else
in F#. It's as idiomatic as things can get. Most people do highlightmatch
expressions when talking about F#, so it may seem thatifs
are discouraged, but that's not really the right way to think of things.That's true that
match
expressions are powerful. It doesn't take much to benefit from using them instead ofifs
when:That said using the construct below should be called out in a code review (and rightly so - this should have been an if):
It's roughly on the same level of code smelliness as the dreaded construction you might sometimes see in bad c-style lang code:
I don't see a problem in your second snippet with nested ifs. That said, there might be better solutions, but it's hard to suggest one when talking about
do somethings
andconditionBs
.