forked from tweag/nickel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
std.ncl
2938 lines (2460 loc) · 85.5 KB
/
std.ncl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Nickel standrd library. This file is included at compile-time in the nickel
# binary and populates the `std` entry in the initial environment.
#
# It would be nice to split this module file into separate files, such as
# `array.ncl`, `contract.ncl`, etc. However, we can't rely on normal imports for
# that, because Nickel would need to find those file at run-time (the whole
# point of embedding the stdlib into the binary is to avoid having to think
# about where to find those files).
#
# One possibility would be to assemble the std module from the files
# programmatically, but then error reporting and the LSP would be impacted in a
# bad way (in particular, breaking the contract of a stdlib function would point
# to generated code that is nowhere accessible to the user).
#
# Another solution is to have special imports, like `<std/array.ncl>`. This is a
# possible direction.
#
# In the meantime, we choose to have this one big monolithic `std` module. This
# choice doesn't negatively impact Nickel users (the file can be browsed looking
# for error locations, typechecking and the LSP are happy because no code is
# programmatically generated). It's just less nice to maintain.
#
# ## Typing
#
# Stdlib modules shouldn't recursively refer to other modules directly, they
# should use the stdlib provided in the environment instead. This means using
# `std.array` from within the `record` module instead of just `array`. While the
# latter could work in principle, typechecking mutually recursive records is
# just harder, and the chances are this won't typecheck.
#
# On the other hand, the `std` module in the environment is properly typed, as
# the typed interface is elaborated upfront.
#
# ## Both a type annotation and a contract annotation
#
# [^type-and-contract]: Some functions have both a static type annotation and
# an additional contract. The additional contract annotation is ignored by
# typechecking, and with respect to static typing, only the static type
# annotation matters.
#
# However, static types are often not enough to check more advanced
# preconditions (e.g. that the argument of `array.drop_first` is a non-empty
# array). In this case, a second contract is used to only check those additional
# properties at runtime, while preserving the static typechecking behavior.
#
# cf https://github.com/tweag/nickel/issues/1354
{
array = {
NonEmpty
| doc m%"
Enforces that an array is not empty.
# Examples
```nickel
([] | std.array.NonEmpty) =>
error
([ 1 ] | std.array.NonEmpty) =>
[ 1 ]
```
"%
= fun label value =>
if %typeof% value == 'Array then
if %length% value != 0 then
value
else
%blame% (%label_with_message% "empty array" label)
else
%blame% (%label_with_message% "not a array" label),
first
: forall a. Array a -> a
| NonEmpty -> Dyn
| doc m%"
Returns the first element of an array.
# Examples
```nickel
std.array.first [ "this is the head", "this is not" ] =>
"this is the head"
```
"%
= fun array => %elem_at% array 0,
last
: forall a. Array a -> a
| NonEmpty -> Dyn
| doc m%"
Returns the last element of an array.
# Examples
```nickel
std.array.last [ "this is the head", "this is not" ] =>
"this is not"
```
"%
= fun array => %elem_at% array (%length% array - 1),
drop_first
: forall a. Array a -> Array a
| NonEmpty -> Dyn
| doc m%"
Returns the given array without its first element.
# Examples
```nickel
std.array.drop_first [ 1, 2, 3 ] =>
[ 2, 3 ]
```
"%
= fun array => %array_slice% 1 (%length% array) array,
drop_last
: forall a. Array a -> Array a
| NonEmpty -> Dyn
| doc m%"
Returns the given array without its last element.
# Examples
```nickel
std.array.drop_last [ 1, 2, 3 ] =>
[ 1, 2 ]
```
"%
= fun array => %array_slice% 0 (%length% array - 1) array,
length
: forall a. Array a -> Number
| doc m%"
Returns the length of an array.
# Examples
```nickel
std.array.length [ "Hello,", " World!" ] =>
2
```
"%
= fun l => %length% l,
map
: forall a b. (a -> b) -> Array a -> Array b
| doc m%"
Applies a function to every element in the given array. That is,
`map f [ x1, x2, ..., xn ]` is `[ f x1, f x2, ..., f xn ]`.
# Examples
```nickel
std.array.map (fun x => x + 1) [ 1, 2, 3 ] =>
[ 2, 3, 4 ]
```
"%
= fun f l => %map% l f,
at
: forall a. Number -> Array a -> a
| std.contract.unstable.IndexedArrayFun
| doc m%"
Retrieves the n-th element from an array, with indices starting at 0.
# Examples
```nickel
std.array.at 3 [ "zero", "one", "two", "three", "four" ] =>
"three"
```
"%
= fun n l => %elem_at% l n,
concat
: forall a. Array a -> Array a -> Array a
| doc m%"
Appends the second array to the first one.
# Examples
```nickel
std.array.concat [ 1, 2, 3 ] [ 4, 5, 6 ] =>
[ 1, 2, 3, 4, 5, 6 ]
```
"%
= fun l1 l2 => l1 @ l2,
fold_left
: forall a b. (a -> b -> a) -> a -> Array b -> a
| doc m%"
Folds a function over an array. In a functional language like Nickel,
folds serve a similar purpose to loops or iterators. `fold_left`
iterates over an array, by repeatedly applying a function to each
element, threading an additional arbitrary state (the accumulator, of
type `a` in the signature) through the chain of applications.
`fold_left f init [x1, x2, ..., xn]` results in `f (... (f (f init x1) x2) ...) xn`.
This function is strict in the intermediate accumulator.
# Left vs right
Folds come in two variants, left and right. How to decide which one to
use?
- If the folded function isn't associative (such as subtraction), then
each variant will give a different result. The choice is dictacted by
which one you need. For example:
```nickel
std.array.fold_right (-) 0 [1, 2, 3, 4]
=> -2
std.array.fold_left (-) 0 [1, 2, 3, 4]
=> -10
```
- If the folded function is associative, both `fold_right` and
`fold_left` return the same result. In that case, **`fold_left` is
generally preferred**, because it forces the evaluation of the
intermediate results resulting in less memory consumption and overall
better performance (outside of pathological cases).
`fold_left` also iterates from the start of the array, which
correponds to the usual behavior of loops and iterators in most
programming languages. There is one case where `fold_right` might be
preferred, see the next point.
- If the folded function is associative but _(left) short-circuiting_,
meaning that it can sometimes determine the result without using the
right argument, then `fold_right` provides early return. An example is
the boolean AND operator `&&`: when evaluating `left && right`, if
`left` is `false`, the whole expression will evaluate to `false`
without even evaluating `right`. Consider the following expression:
```nickel
std.array.replicate 1000 true
# gives [false, .. true 1000 times]
|> std.array.prepend false
|> std.array.fold_right (&&) [false]
```
Here, `fold_right` will stop at the first element, and the operation
runs in constant time, given the definition of `fold_right` and the
lazy evaluation of Nickel. If we had used `fold_left` instead, which
is closer to a standard iterator, we would have iterated over all of
the 1000 elements of the array.
# Examples
```nickel
fold_left (fun acc e => acc + e) 0 [ 1, 2, 3 ] =>
(((0 + 1) + 2) 3) =>
6
```
"%
= fun f acc array =>
let length = %length% array in
if length == 0 then
acc
else
let rec go = fun acc n =>
if n == length then
acc
else
let next_acc =
%elem_at% array n
|> f acc
in
go next_acc (n + 1)
|> %seq% next_acc
in
go acc 0,
fold_right
: forall a b. (a -> b -> b) -> b -> Array a -> b
| doc m%"
Folds a function over an array. Folds serve a similar purpose to loops or
iterators in a functional language like Nickel. `fold_right` iterates
over an array by repeatedly applying a function to each element and
threading an additional arbitrary state (the accumulator of type `a` in
the signature) through the chain of applications.
`fold_right f init [x1, x2, ..., xn]` results in `f x1 (f x2 (... (f xn init) ...))`.
# Left vs right
Folds come in two variants, left and right. How to decide which one to
use? Please refer to the documentation of `fold_left`.
# Examples
```nickel
std.array.fold_right (fun e acc => acc @ [e]) [] [ 1, 2, 3 ] =>
((([] @ [3]) @ [2]) @ [1]) =>
[ 3, 2, 1 ]
```
"%
= fun f fst l =>
let length = %length% l in
let rec go = fun n =>
if n == length then
fst
else
go (n + 1)
|> f (%elem_at% l n)
in go 0,
prepend
: forall a. a -> Array a -> Array a
| doc m%"
Builds an array given the first element and the rest of the array.
# Examples
```nickel
std.array.prepend 1 [ 2, 3 ] =>
[ 1, 2, 3 ]
```
"%
= fun x l => [x] @ l,
append
: forall a. a -> Array a -> Array a
| doc m%"
Builds an array given the last element and the rest of the array.
# Examples
```nickel
std.array.append 3 [ 1, 2 ] =>
[ 1, 2, 3 ]
```
"%
= fun x l => l @ [x],
reverse
: forall a. Array a -> Array a
| doc m%"
Reverses an array.
# Examples
```nickel
std.array.reverse [ 1, 2, 3 ] =>
[ 3, 2, 1 ]
```
"%
= fun l => fold_left (fun acc e => [e] @ acc) [] l,
filter
: forall a. (a -> Bool) -> Array a -> Array a
| doc m%"
`filter f xs` returns an array containing all elements from `xs` that satisfy `f`.
# Examples
```nickel
std.array.filter (fun x => x <= 3) [ 4, 3, 2, 5, 1 ] =>
[ 3, 2, 1 ]
```
"%
= fun pred l => fold_left (fun acc x => if pred x then acc @ [x] else acc) [] l,
flatten
: forall a. Array (Array a) -> Array a
| doc m%"
Concatenates all elements of an array of arrays.
# Examples
```nickel
std.array.flatten [[1, 2], [3, 4]] =>
[1, 2, 3, 4]
```
"%
= fun l => fold_right (fun l acc => l @ acc) [] l,
all
: forall a. (a -> Bool) -> Array a -> Bool
| doc m%"
Returns `true` if all elements in the given array satisfy the predicate,
`false` otherwise.
# Examples
```nickel
std.array.all (fun x => x < 3) [ 1, 2 ] =>
true
std.array.all (fun x => x < 3) [ 1, 2, 3 ] =>
false
```
"%
= fun pred l => fold_right (fun x acc => if pred x then acc else false) true l,
any
: forall a. (a -> Bool) -> Array a -> Bool
| doc m%"
Returns `true` if at least one element in the given array satisfies
the predicate, `false` otherwise.
# Examples
```nickel
std.array.any (fun x => x < 3) [ 1, 2, 3, 4 ] =>
true
std.array.any (fun x => x < 3) [ 5, 6, 7, 8 ] =>
false
```
"%
= fun pred l => fold_right (fun x acc => if pred x then true else acc) false l,
# **Warning**: unless you know what you're doing, please don't change the
# type of `elem` to be polymorphic.
#
# `elem` must operate on elements of type `Dyn` only, because `elem` performs
# equality tests, and those aren't allowed on generic variables (as it
# breaks parametricity).
#
# However, as a current work-around to use equality easily in typed code,
# `(==)` has type `forall a. a -> a -> Bool`. We could
# be tempted to assign the type `elem : forall a. a -> Array a -> Bool`, but
# that would be lying (as `==` is currently lying as well), and more
# importantly, the contract will fail on any non-trivial call at run-time.
elem
: Dyn -> Array Dyn -> Bool
| doc m%"
Returns `true` if the given value appears in the array, `false` otherwise.
# Examples
```nickel
std.array.elem 3 [ 1, 2, 3, 4, 5 ] =>
true
```
"%
= fun elt => any (fun x => x == elt),
partition
: forall a. (a -> Bool) -> Array a -> { right : Array a, wrong : Array a }
| doc m%"
Partitions an array into two new arrays. `right` will contain all
elements that satisfy the predicate, while `wrong` will contain those
that do not.
# Examples
```nickel
std.array.partition (fun x => x < 5) [ 2, 4, 5, 3, 7, 8, 6 ] =>
{ right = [ 2, 4, 3 ], wrong = [ 5, 7, 8, 6 ] }
```
"%
= fun pred l =>
let aux = fun acc x =>
if (pred x) then
{ right = acc.right @ [x], wrong = acc.wrong }
else
{ right = acc.right, wrong = acc.wrong @ [x] }
in
fold_left aux { right = [], wrong = [] } l,
generate
: forall a. (Number -> a) -> Number -> Array a
| Dyn -> std.number.Nat -> Dyn
| doc m%"
`generate f n` returns an array of length `n` by applying `f` to the
integers from `0` to `n-1`. That is, `generate f n` is
`[ f 0, f 1, ..., f (n - 1)]`
# Examples
```nickel
std.array.generate (fun x => x * x) 4 =>
[ 0, 1, 4, 9 ]
```
"%
= fun f n => %generate% n f,
sort
: forall a. (a -> a -> [| 'Lesser, 'Equal, 'Greater |]) -> Array a -> Array a
| doc m%"
Sorts an array based on the provided comparison operator.
# Examples
```nickel
std.array.sort (fun x y =>
if x < y then
'Lesser
else if (x == y) then
'Equal
else
'Greater)
[ 4, 5, 1, 2 ]
=> [ 1, 2, 4, 5 ]
```
"%
#TODO: maybe inline partition to avoid contract checks?
= fun cmp array =>
let length = %length% array in
let first = %elem_at% array 0 in
let rest = %array_slice% 1 length array in
let parts = partition (fun x => (cmp x first == 'Lesser)) rest in
if length <= 1 then
array
else
(sort cmp (parts.right)) @ [first] @ (sort cmp (parts.wrong)),
flat_map
: forall a b. (a -> Array b) -> Array a -> Array b
| doc m%"
First `map` the given function over the array and then `flatten` the
result.
# Examples
```nickel
std.array.flat_map (fun x => [x, x]) [1, 2, 3]
=> [1, 1, 2, 2, 3, 3]
```
"%
= fun f xs => map f xs |> flatten,
intersperse
: forall a. a -> Array a -> Array a
| doc m%"
Intersperses a value between the elements of an array.
# Examples
```nickel
std.array.intersperse ", " [ "Hello", "wonderful", "world!" ]
=> [ "Hello", ", ", "wonderful", ", ", "world!" ]
std.array.intersperse ", " [ "Hello" ]
=> [ "Hello" ]
std.array.intersperse ", " []
=> []
```
"%
= fun v array =>
let length = %length% array in
if length <= 1 then
array
else
let first = %elem_at% array 0 in
let rest = %array_slice% 1 length array in
[first] @ (flat_map (fun a => [v, a]) rest),
slice
: forall a. Number -> Number -> Array a -> Array a
| std.contract.unstable.ArraySliceFun
| doc m%"
`slice start end array` returns the slice of `array` between `start` (included) and
`end` (excluded).
# Preconditions
In `slice start end value`, `start` and `end` must be positive
integers such that `0 <= start <= end <= std.array.length value`.
# Examples
```nickel
std.array.slice 1 3 [ 0, 1, 2, 3, 4, 5]
=> [ 1, 2 ]
std.array.slice 0 3 [ "Hello", "world", "!" ]
=> [ "Hello", "world", "!" ]
std.array.slice 2 3 [ "Hello", "world", "!" ]
=> [ "!" ]
```
"%
= fun start end value => %array_slice% start end value,
split_at
: forall a. Number -> Array a -> { left : Array a, right : Array a }
| std.contract.unstable.IndexedArrayFun
| doc m%"
Splits an array in two at a given index and puts all the elements
to the left of the element at the given index (excluded) in the
`left` field, and the rest of the array in the `right` field.
# Preconditions
In `split_at inded value`, `index` must be a positive integer such
that `0 <= index <= std.array.length value`.
# Examples
```nickel
std.array.split_at 2 [ 0, 1, 2, 3, 4, 5]
=> { left = [ 0, 1 ], right = [ 2, 3, 4, 5 ] }
std.array.split_at 0 [ "Hello", "world", "!" ]
=> { left = [ ], right = [ "Hello", "world", "!" ] }
std.array.split_at 3 [ "Hello", "world", "!" ]
=> { left = [ "Hello", "world", "!" ], right = [ ] }
```
"%
= fun index value =>
{
left = %array_slice% 0 index value,
right = %array_slice% index (%length% value) value
},
replicate
: forall a. Number -> a -> Array a
| std.number.Nat -> Dyn
| doc m%"
`replicate n x` creates an array containing `x` exactly `n` times.
# Preconditions
`n` must be an integer greater or equal to `0`.
# Examples
```nickel
std.array.replicate 0 false
=> [ ]
std.array.replicate 5 "x"
=> [ "x", "x", "x", "x", "x" ]
```
"%
= fun n x => %generate% n (fun _i => x),
range_step
: Number -> Number -> Number -> Array Number
| std.contract.unstable.RangeFun (std.contract.unstable.RangeStep -> Dyn)
| doc m%"
`range_step start end step` generates the array of numbers
`[start, start + step, start + 2*step, ..]` up to the first element
(excluded) larger than or equal to `end`
# Preconditions
In `range_step start end step`, `start` and `end` must satisfy `start
<= end`. `step` must be strictly greater than `0`.
# Examples
```nickel
std.array.range_step (-1.5) 2 0.5
=> [ -1.5, -1, -0.5, 0, 0.5, 1, 1.5 ]
```
"%
= fun start end step =>
%generate%
((end - start) / step |> std.number.floor)
(fun i => start + i * step),
range
: Number -> Number -> Array Number
| std.contract.unstable.RangeFun Dyn
| doc m%"
`range start end` generates the array of numbers
`[start, start + 1, start + 2, ..]` up to the first element
(excluded) larger than or equal to `end`.
`range start end` is equivalent to `range_step start end 1`.
# Preconditions
In `range_step start end`, `start` and `end` must satisfy
`start <= end`.
# Examples
```nickel
std.array.range 0 5
=> [ 0, 1, 2, 3, 4 ]
```
"%
= fun start end => range_step start end 1,
reduce_left
: forall a. (a -> a -> a) -> Array a -> a
| Dyn -> NonEmpty -> Dyn
| doc m%"
Reduces the elements to a single one, by repeatedly applying a
reducing operation.
`reduce_left` associates to the left, that is
`reduce_left op [x1, x2, ..., xn]` results in `op (... (op (op x1 x2) x3) ...) xn`.
`reduce_left` is the same as `fold_left`, but uses the first element as
the initial accumulator.
# Preconditions
The provided array must be non-empty.
# Left vs right
The rationale to decide between `fold_left` and `fold_right` applies to
`reduce_left` and `reduce_right` as well. See the documentation of
`fold_left`.
# Examples
```nickel
std.array.reduce_left (@) [ [1, 2], [3], [4,5] ]
=> (([1, 2] @ [3]) @ [4,5])
=> [ 1, 2, 4, 5 ]
std.array.reduce_left (-) [ 1, 2, 3, 4]
=> ((1 - 2) - 3) - 4
=> -8
```
"%
= fun f array =>
let first = %elem_at% array 0 in
let rest = %array_slice% 1 (%length% array) array in
fold_left f first rest,
reduce_right
: forall a. (a -> a -> a) -> Array a -> a
| Dyn -> NonEmpty -> Dyn
| doc m%"
Reduces the elements to a single one, by repeatedly applying a reducing
operation.
`reduce_right` associates to the right, that is
`reduce_right op [x1, x2, ..., xn]` results in
`op x1 (op x2 (... (op xn-1 xn) ...))`.
`reduce_right` is the same as `fold_right`, but uses the last element as
the initial element.
# Preconditions
The provided array must be non-empty.
# Left vs right
The rationale to decide between `fold_left` and `fold_right` applies to
`reduce_left` and `reduce_right` as well. See the documentation of
`fold_left`.
# Examples
```nickel
std.array.reduce_right (@) [ [1, 2], [3], [4,5] ]
=> [1, 2] @ ([3] @ [4,5])
=> [ 1, 2, 4, 5 ]
std.array.reduce_right (-) [ 1, 2, 3, 4]
=> 1 - (2 - (3 - 4))
=> -2
```
"%
= fun f array =>
let last_index = %length% array - 1 in
let last = %elem_at% array last_index in
let rest = %array_slice% 0 last_index array in
fold_right f last rest,
},
contract = {
Equal
| doc m%"
`Equal` is a contract enforcing equality to a given constant.
`Equal` is lazy over arrays and records. When checking such values,
`Equal` doesn't test for equality of elements right away (it just tests
that the size is the same for arrays and that fields are the same for
records), but returns a new value where equality subcontracts have been
pushed inside each element.
# Example
```nickel
1 + 4 | std.contract.Equal 5
=> 5
4 | std.contract.Equal 5
=> error: contract broken by a value
```
"%
=
let fields_diff
| doc m%"
Compute the difference between the fields of two records.
`fields_diff` isn't concerned with the actual values themselves, but
just with field names.
Return a record of type
`{extra : Array String, missing: Array String}`, relative to the
first argument `constant`.
"%
= fun constant value =>
let diff =
value
|> std.record.fields
|> std.array.fold_left
(
fun acc field =>
if std.record.has_field field acc.rest then
{
extra = acc.extra,
rest = std.record.remove field acc.rest,
}
else
{
extra = std.array.append field acc.extra,
rest = acc.rest,
}
)
{ extra = [], rest = constant }
in
{ extra = diff.extra, missing = std.record.fields diff.rest }
in
let blame_fields_differ = fun qualifier fields ctr_label =>
let plural = if %length% fields == 1 then "" else "s" in
ctr_label
|> label.with_message "%{qualifier} field%{plural} `%{std.string.join ", " fields}`"
|> label.append_note "`std.contract.Equal some_record` requires that the checked value is equal to the record `some_record`, but the sets of their fields differ."
|> blame
in
fun constant =>
let constant_type = %typeof% constant in
let check_typeof_eq = fun ctr_label value =>
let value_type = %typeof% value in
if value_type == constant_type then
value
else
ctr_label
|> label.with_message "expected `%{%to_str% constant_type}`, got `%{%to_str% value_type}`"
|> label.append_note "`std.contract.Equal some_value` requires that the checked value is equal to `some_value`, but they don't have the same type."
|> blame
in
constant_type
|> match {
'Record =>
# we map the constant from {field1 = val1, .., fieldn = valn} to
# {field1 = Equal val1, .., fieldn = Equal valn}, building a
# dictionary of equality contracts
let contract_map = %record_map% constant (fun _key => Equal) in
fun ctr_label value =>
let value = check_typeof_eq ctr_label value in
let diff = fields_diff constant value in
if %length% diff.extra != 0 then
blame_fields_differ "extra" diff.extra ctr_label
else if %length% diff.missing != 0 then
blame_fields_differ "missing" diff.missing ctr_label
else
%record_lazy_assume%
ctr_label
value
(
fun field =>
contract_map."%{field}"
),
'Array =>
fun ctr_label value =>
let value = check_typeof_eq ctr_label value in
let value_length = %length% value in
if value_length == %length% constant then
%generate%
value_length
(
fun i =>
%elem_at% value i
|> std.contract.apply (Equal (%elem_at% constant i)) ctr_label
)
else
ctr_label
|> label.with_message "array length mismatch (expected `%{%to_str% (%length% constant)}`, got `%{%to_str% value_length})`"
|> label.append_note "`std.contract.Equal some_array` requires that the checked value is equal to the array `some_array`, but their lengths differ."
|> blame,
# Outside of lazy data structures, we just use (==)
_ =>
fun ctr_label value =>
value
|> check_typeof_eq ctr_label
|> from_predicate ((==) constant) ctr_label,
},
blame
| doc m%"
Raises blame for a given label.
Type: `forall a. Label -> a`
(for technical reasons, this function isn't actually statically typed)
Blame is the mechanism to signal contract violation in Nickel. It
ends the program execution and prints a detailed report thanks to the
information tracked inside the label.
# Examples
```nickel
IsZero = fun label value =>
if value == 0 then
value
else
std.contract.blame label
```
"%
= fun label => %blame% label,
blame_with_message
| doc m%"
Raises blame with respect to a given label with a custom error message.
Type: `forall a. String -> Label -> a`
(for technical reasons, this function isn't actually statically typed)
Same as `blame`, but takes an additional error message that will be
displayed as part of the blame error. `blame_with_message message label`
is equivalent to `blame (label.with_message message label)`
# Examples
```nickel
let IsZero = fun label value =>
if value == 0 then
value
else
std.contract.blame_with_message_message "Not zero" label
in
0 | IsZero
```
"%
= fun message label => %blame% (%label_with_message% message label),
from_predicate
| doc m%"
Generates a contract from a boolean predicate.
Type: `(Dyn -> Bool) -> (Label -> Dyn -> Dyn)`
(for technical reasons, this function isn't actually statically typed)
# Examples
```nickel
let IsZero = std.contract.from_predicate (fun x => x == 0) in
0 | IsZero
```
"%
= fun pred label value => if pred value then value else %blame% label,
label
| doc m%"
The label submodule provides functions that manipulate the label
associated with a contract application.
A label is a special opaque value automatically passed by the Nickel
interpreter to contracts when performing a contract check.
A label stores a stack of custom error diagnostics, that can be
manipulated by the functions in this module. Labels thus offer a way to
customize the error message that will be shown if a contract is broken.
The setters (`with_XXX` functions) always operate on the current error
diagnostic, which is the last diagnotic on the stack. If the stack is
empty, a fresh diagnostic is silently created when using a setter.
The previous diagnostics on the stack are considered archived, and
can't be modified anymore. All diagnostics will be shown during error
reporting, with the most recent being used as the main one.
`std.contract.apply` is the operation that pushes a new fresh diagnostic on
the stack, saving the previously current error diagnostic. The function
`std.contract.apply` is typically used to apply subcontracts inside a parent
contract. Stacking the current diagnostic potentially customized by
the parent contract saves the information inside, and provides a fresh
diagnostic for the child contract to use.
"%
= {
with_message
| doc m%"
Attaches a custom error message to the current error diagnostic of a
label.
Type: `String -> Label -> Label`
(for technical reasons, this function isn't actually statically typed)
If a custom error message was previously set, there are two
possibilities:
- the label has gone through a `std.contract.apply` call in-between.
In this case, the previous diagnostic has been stacked, and
using `with_message` won't erase anything but rather modify
the fresh current diagnostic.
- no `std.contract.apply` has taken place since the last message
was set. In this case, the current diagnostic's error message
is replaced.
# Examples
```nickel
let ContractNum = std.contract.from_predicate (fun x => x > 0 && x < 50) in
let Contract = fun label value =>
if std.is_number value then
std.contract.apply
ContractNum
(std.contract.label.with_message
"num subcontract failed! (out of bound)"
label
)
value
else
value
in