Skip to content

Commit

Permalink
Add get field value from record with default
Browse files Browse the repository at this point in the history
* Format getor function and add example
* Add get_or function for records
* Add at_or returing n-th value or default
  • Loading branch information
olorin37 committed May 21, 2024
1 parent 8d88d63 commit fa7e379
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions core/stdlib/std.ncl
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,25 @@
"%
= fun n l => %elem_at% l n,

at_or
: forall a. Number -> a -> Array a -> a
| doc m%"
Retrieves the n-th element from an array, with indices starting at 0
or provided value in case index is out of bounds.

# Examples

```nickel
std.array.at 3 "default" [ "zero", "one" ] =>
"default"
```
"%
= fun n default_value array =>
if n < %length% array then
%elem_at% array n
else
default_value,

concat
: forall a. Array a -> Array a -> Array a
| doc m%"
Expand Down Expand Up @@ -2148,6 +2167,28 @@
"%%
= fun field r => r."%{field}",

get_or
: forall a. String -> a -> { _ : a } -> a
| doc m%%"
Returns the field of a record with given name or default value,
if there is no such field.

# Examples

```nickel
std.record.get_or "tree" 3 { one = 1, two = 2 } =>
3

std.record.get_or "one" 11 { one = 1, two = 2 } =>
1
```
"%%
= fun field default_value record =>
if %has_field% field record then
record."%{field}"
else
default_value,

insert
: forall a. String -> a -> { _ : a } -> { _ : a }
| doc m%%"
Expand Down

0 comments on commit fa7e379

Please sign in to comment.