Skip to content

Commit

Permalink
add std.contract.Sequence (#1452)
Browse files Browse the repository at this point in the history
* add std.contract.Sequence

* nickel lists have `,`

Co-authored-by: Viktor Kleen <viktor.kleen@tweag.io>

* eta reduction

Co-authored-by: Yann Hamdaoui <yann.hamdaoui@tweag.io>

* example where it's actually useful

* capitalisation

---------

Co-authored-by: Viktor Kleen <viktor.kleen@tweag.io>
Co-authored-by: Yann Hamdaoui <yann.hamdaoui@tweag.io>
  • Loading branch information
3 people committed Jul 20, 2023
1 parent da07e3e commit 5002968
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
35 changes: 35 additions & 0 deletions core/stdlib/std.ncl
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,41 @@
"%
= fun pred label value => if pred value then value else %blame% label,

Sequence
| doc m%"
Apply multiple contracts from left to right.

Type: `Array Contract -> Contract`
(for technical reasons, this function isn't actually statically typed)

# Examples

```nickel
x | std.contract.Sequence [ Foo, Bar ]
```

is equivalent to

```nickel
(x | Foo) | Bar
```

This is useful in positions where one cannot apply multiple contracts,
such as an argument to another contract:

```nickel
x | Array (std.contract.Sequence [ Foo, Bar ])
```

Or stored in a variable:

```nickel
let C = std.contract.Sequence [ Foo, Bar ] in
x | C
```
"%
= fun contracts label value =>
std.array.fold_right (fun contract => std.contract.apply contract label) value contracts,
label
| doc m%"
The label submodule provides functions that manipulate the label
Expand Down
6 changes: 6 additions & 0 deletions core/tests/integration/fail/contracts/sequence.ncl
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# test.type = 'error'
#
# [test.metadata]
# error = 'EvalError::BlameError'

3 | std.contract.Sequence [ Number, std.contract.from_predicate (fun x => x < 5), std.contract.from_predicate (fun x => x > 5) ]
6 changes: 6 additions & 0 deletions core/tests/integration/pass/contracts/contracts.ncl
Original file line number Diff line number Diff line change
Expand Up @@ -166,5 +166,11 @@ let {check, Assert, ..} = import "../lib/assert.ncl" in
= fun r => %record_insert% "g" r g in
let res = f { z = 3 }
in true,

# std.contract.Sequence
let three = 3 | std.contract.Sequence [ Number, std.contract.from_predicate (fun x => x < 5) ] in
# preserves order
let tag = "some_tag" | std.contract.Sequence [ std.enum.TagOrString, [| 'some_tag |] ]
in true
]
|> check

0 comments on commit 5002968

Please sign in to comment.