facebook / facebook/flow

Pure functions

Open
#2,715 10 comments 56 reactions 0 assignees View on GitHub
feature request Typing: refinements
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

This is a feature request for marking functions as not having any side effects, aka being pure.

Flow reports the following safe code as unsafe:

```
/* @flow */
type T = { func: ?(number) => void };
function f() { return 7; }
function g(val: T) {
if (val.func) {
val.func(f());
}
}
```

The reasoning for this is because Flow has no idea who else has a reference to `val`, and the call to `f` might modify the value of `val.func`, so the previous non-null assertion is invalidated.

It would be nice to be able to mark functions as `pure`. Flow could assert that:
- no variables outside the local scope are modified (including properties of objects)
- no non-pure functions are called

As a straw man syntax for this, I suggest `pure` before the return type in the type definition:

```
type APureFunction: () => pure void
function aPureFunction(): pure void { }
```

I don't think this is a duplicate of #18 because that focuses on data immutability, which is different from function purity.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.