Skip to content

Commit

Permalink
firstSome infix operator
Browse files Browse the repository at this point in the history
  • Loading branch information
jonlaing committed Nov 18, 2017
1 parent 22eb899 commit aae98dd
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,27 @@ let lastEqual = (xs, ys) =>
Some(Util.eq) <*> RList.last(xs) <*> RList.last(ys) |> Option.default(false);
```

### Translating JS Idioms

### Or chains

Take the following example in Javascript:

```Javascript
let x = a || b || c || d;
```

We can't translate that directly to Reason, because there is no `null` or `undefined` in Reason.
The closest approximation would be `option`, in which we can string together `Some` and `None`
to get the first one that is `Some`.

There is a helper function called `firstSome` and its infix variation `|?` that do exactly this.

```Reason
/* a, b, and c are all options, but d is not */
let x = a |? b |? c |> default(d);
```

Reference
--------------------------------------------------------------------------------

Expand All @@ -161,3 +182,4 @@ Reference
- `||>`: Point-free Function Pipe
- `-<<`: Lens Compose
- `>>-`: Lens Pipe
- `|?`: Optional Or
1 change: 1 addition & 0 deletions src/Option.re
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,5 @@ module Infix = {
let (>>=) = (>>=);
let (<$>) = (<$>);
let (<*>) = (<*>);
let (|?) = firstSome;
};
1 change: 1 addition & 0 deletions src/Option.rei
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,5 @@ module Infix: {
let (>>=): (option('a), 'a => option('b)) => option('b);
let (<$>): (option('a), 'a => 'b) => option('b);
let (<*>): (option(('a => 'b)), option('a)) => option('b);
let (|?): (option('a), option('a)) => option('a);
};

0 comments on commit aae98dd

Please sign in to comment.