Open mattnewport opened 1 year ago
If you really want functions like this, just add them in an auxiliary module
module Option =
let thenSome (value: 'T) (cond: bool) : 'T option =
if cond then Some value else None
let thenSomeWith (thunk: unit -> 'T) (cond: bool) : 'T option =
if cond then Some (thunk()) else None
I propose we ...
Add functions similar to
then()
andthen_some()
onbool
in Rust which take a bool and return an option which isNone
if thebool
isfalse
andSome f()
orSome x
if the bool is true.Alternative names:
Option.fromBool
/Option.fromBoolWith
The existing way of approaching this problem in F# is ...
let opt = if x < 10 then Some x else None
Which becomes:
let opt' = x < 10 |> Option.thenSome x
Pros and Cons
The advantages of making this adjustment to F# are ...
It makes it a bit nicer to write pipelined code that needs to convert a bool value to an option. An example:
The alternative way to write this using
if ... then ... else
:I suggest that the version using
Option.thenSome
emphasizes the important part of the logic and gets rid of the repetitiveelse None
branches that are really just noise here.Another use can be seen in this alternative approach to implementing
fizzBuzz
using active patterns, whereOption.thenSome
makes the active pattern function implementations a bit cleaner:An example of using
Option.thenSomeWith
to avoid evaluation when the condition is false:Here's classify with
if ... then ... else
:Again the difference is fairly minor but we eliminate some noise with
None
s andSome
s.The disadvantages of making this adjustment to F# are ...
This is a minor improvement and easily implemented in user code rather than in the library.
Extra information
Estimated cost (XS, S, M, L, XL, XXL):
S
Related suggestions: (put links to related suggestions here)
1041
The
Option.thenSome
function is a simpler way to get some of the benefits of issue 1041 for active patterns that are based on a simple boolean condition.Affidavit (please submit!)
Please tick this by placing a cross in the box:
Please tick all that apply:
For Readers
If you would like to see this issue implemented, please click the :+1: emoji on this issue. These counts are used to generally order the suggestions by engagement.