Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions src/purity-reflection.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,22 @@ For example, here is the implementation of `Set.count`:
```flix
@ParallelWhenPure
pub def count(f: a -> Bool \ ef, s: Set[a]): Int32 \ ef =
typematch f {
case g: a -> Bool \ {} =>
let h = (k, _) -> g(k);
let Set(t) = s;
RedBlackTree.parCount(threads() - 1, h, t)
case g: a -> Bool \ ef => foldLeft((b, k) -> if (g(k)) b + 1 else b, 0, s)
case _: _ => unreachable!()
match purityOf(f) {
case Purity.Pure(g) =>
if (useParallelEvaluation(s))
let h = (k, _) -> g(k);
let Set(t) = s;
RedBlackTree.parCount(h, t)
else
foldLeft((b, k) -> if (f(k)) b + 1 else b, 0, s)
case Purity.Impure(g) => foldLeft((b, k) -> if (g(k)) b + 1 else b, 0, s)
}
```

Here the `typematch` construct is used to reflect on the purity of `f`:
Here the `purityOf` function is used to reflect on the purity of `f`:

- If `f` is pure then we evaluate `Set.count` in _parallel_ over the elements of
the set.
the set (if the set is big enough to warrant it).
- If `f` is effectful then we use an ordinary (single-threaded) fold.

The advantage is that we get parallelism for free – _if_ `f` is pure.