I suggest we ...

Introduce the ?. operator into F#

Since we allow the . operator to reference fields and properties of objects in F#, we're faced with the same problem of null checking that plagued C# until C# 5.

The C# 6 'elvis' operator propagates nulls in a succinct way, and I think that working with objects in F# will be similarly simplified if we introduce it here as well!

16 votes
Vote
Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
You have left! (?) (thinking…)
John Azariah shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

6 comments

Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
Submitting...
  • Ryan Riley commented  ·   ·  Flag as inappropriate

    I agree with Bartosz. Even though ?. would be more succinct, I would prefer the built-in language symbols remain as few in number as possible.

  • Bartosz Sypytkowski commented  ·   ·  Flag as inappropriate

    "maybe{}" is a basic lesson about computation expressions and it already solves problems, that "elvis operator" is trying to solve. F# doesn't need to solve monad problems using syntax sugar like C# does. We can use existing tools instead.

  • Colin Bull commented  ·   ·  Flag as inappropriate

    There is already an Option.ofObj(F# 4) that can help here

    You can do something like,

    let a = new System.IO.FileInfo("Foo")

    let (<*>) a f = a |> Option.map f
    let ($) a f = (Option.ofObj a) <*> f

    let x =
    a$(fun x -> x.CreationTime) <*> (fun x -> x.ToShortDateString())

    Not quiet as succinct but you can always lift those accessors to functions to make things tidier.
    In general though I'm opposed to using this type of symbolics as it hides meaning, however well documented it is from (C# etc...). I'd prefer to define these locally like this and just use the functions from F# core.

  • Fraser Waters commented  ·   ·  Flag as inappropriate

    @radek, maybe semantics like

    a.?b
    ===
    if a = null then None else Some (a.b)

    And chained together so

    a.?b.?c
    ===
    if a = null then None else (if b = null then None else Some (a.b.c))

    Would allow easy matching as well:

    match a.?b with
    | Some b -> printf "a.b is %A" b
    | None -> printf "a is null"

F# Language

Feedback and Knowledge Base