Reputation: 351
I have some complex if statement which is not very well readable. it works similar to following example:
let a = 1
let b = 2
let test v = true
if a <> b then a - 1
else
if (test a) then a + 1
else a
Is there a better functional solution? I thought of something like
match a with
| b -> ...
| _ -> ...
but this doesn't work, of course, since b becomes a within that statement.
Upvotes: 2
Views: 187
Reputation: 233237
There's nothing 'unfunctional' about if..then..else
expressions; even Haskell has them ;)
While, as John Palmer's answer shows, you can write
match a with
| foo when foo <> b -> a - 1
| foo when test foo -> a + 1
| _ -> a
you can also write
if a <> b then a - 1
elif test a then a + 1
else a
Personally, in this case I'd prefer the if..then..else
syntax, as it's slightly shorter and (IMO) more concise.
Upvotes: 5
Reputation: 25516
This is how it would look with a match
match a with
|foo when foo=b -> ..
|foo when test foo -> ...
|_ -> a
you need to use when
Upvotes: 3