I suggest we ...

Pure Functions - "pure" keyword

I've been thinking about this one for a while.

At the moment, it's pretty easy to make a pure function and as a long as you follow a few rules, you should be fine. There is just no guarantee. A way for the F# compiler to enforce a function to be "pure" and not allow any side effects/mutations ever would ensure that guarantee. A "pure" function will have more constraints. This may also allow for more aggressive optimizations.

A challenge with this is how do we handle existing functions that are referentially transparent and types that we know are immutable. My best shot at this is only allow the F# compiler to make exceptions to functions/types to be allowed in "pure" functions. An example would be the "string" type and its functions.

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

21 comments

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

    I like this idea. You could say that a pure function does not close over any variables in outer scope, and can only call methods & access properties that are themselves marked as pure. E.g.

    let x = 5
    let printx() = printfn "%i" x // This function is NOT pure

    let pure add x y = x + y // This function is pure because it only acts on variables explicitly passed in, and because the "+" operator is pure.

    type Customer = { Id: Guid; mutable Name: string }

    let pure formatId c = sprintf "The id is %A" c.Id // Immutable properties can be accessed in pure methods

    let formatName c = sprintf "The name is %s" c.Name // Mutable properties make the method non-pure

    This seems more "correct" somehow, but I'm not 100% sure what pure methods would actually give you...

2 Next →

F# Language

Feedback and Knowledge Base