Skip to content

Add match! (match-bang) syntactic sugar to computation expressions [ RFC FS-1047 ] #572

@jwosty

Description

@jwosty

Add a match! syntactic sugar to computation expressions

When writing computation expressions, especially asyncs that call my own functions returning Options, I find myself quite often binding it (via let!), then proceeding to use that variable only one time in a pattern match immediately following. It'd be really nice to eliminate the unnecessary let! and have a sort of match! that means the same thing as a let! followed by a vanilla match.

For example, this:

(val myAsyncTryGetResult: 'a -> Async<'a option>)
async {
    let! x = myAsyncTryGetResult foo
    match x with
    | Some(x) -> printfn "got some: %A" x
    | None -> printfn "got none" }

could instead be written as:

(val myAsyncTryGetResult: 'a -> Async<'a option>)
async {
    match! myAsyncTryGetResult foo with
    | Some(x) -> printfn "got some: %A" x
    | None -> printfn "got none" }

To implement this, the compiler could by default treat it the same as let! followed by match, or spit out a call to a new builder method for this construct if the builder defines it, perhaps called BindPattern. It would be identical in signature to builder.Bind.

E.g. compiler could emit

asyncBuilder.Bind(myAsyncTryGetResult foo, (fun x -> match x with ... ))

or

asyncBuilder.BindPattern(myAsyncTryGetResult foo, (fun x -> match x with ... ))

Pros and Cons

The advantages of making this adjustment to F# are

  • Code that encounters this type of annoyance would be a little cleaner
  • Non-invasive and simple

The disadvantages of making this adjustment to F# are

  • Nonzero effort required :P

Extra information

Estimated cost (XS, S, M, L, XL, XXL): S

Affadavit (must be submitted)

Please tick this by placing a cross in the box:

  • This is not a question (e.g. like one you might ask on stackoverflow) and I have searched stackoverflow for discussions of this issue
  • I have searched both open and closed suggestions on this site and believe this is not a duplicate
  • This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it.

Please tick all that apply:

  • This is not a breaking change to the F# language design
  • I would be willing to help implement and/or test this
  • I or my company would be willing to help crowdfund F# Software Foundation members to work on this

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions