@@ -527,6 +527,92 @@ if (exit === 1) {
527
527
528
528
</CodeTab >
529
529
530
+ ### Match on Array
531
+
532
+ <CodeTab labels = { [" ReScript" , " JS Output" ]} >
533
+
534
+ ``` res example
535
+ let students = ["Jane", "Harvey", "Patrick"]
536
+ switch students {
537
+ | [] => Js.log("There are no students")
538
+ | [student1] =>
539
+ Js.log("There's a single student here: " ++ student1)
540
+ | manyStudents =>
541
+ // display the array of names
542
+ Js.log2("The students are: ", manyStudents)
543
+ }
544
+ ```
545
+ ``` js
546
+ var students = [" Jane" , " Harvey" , " Patrick" ];
547
+
548
+ var len = students .length ;
549
+
550
+ if (len !== 1 ) {
551
+ if (len !== 0 ) {
552
+ console .log (" The students are: " , students);
553
+ } else {
554
+ console .log (" There are no students" );
555
+ }
556
+ } else {
557
+ var student1 = students[0 ];
558
+ console .log (" There's a single student here: " + student1);
559
+ }
560
+ ```
561
+
562
+ </CodeTab >
563
+
564
+ ### Match on List
565
+
566
+ Pattern matching on list is similar to array, but with the extra feature of extracting the tail of a list (all elements except the first one):
567
+
568
+ <CodeTab labels = { [" ReScript" , " JS Output" ]} >
569
+
570
+ ``` res example
571
+ let rec printStudents = (students) => {
572
+ switch students {
573
+ | list{} => () // done
574
+ | list{student} => Js.log("Last student: " ++ student)
575
+ | list{student1, ...otherStudents} =>
576
+ Js.log(student1)
577
+ printStudents(otherStudents)
578
+ }
579
+ }
580
+ printStudents(list{"Jane", "Harvey", "Patrick"})
581
+ ```
582
+ ``` js
583
+ function printStudents (_students ) {
584
+ while (true ) {
585
+ var students = _students;
586
+ if (! students) {
587
+ return ;
588
+ }
589
+ var otherStudents = students .tl ;
590
+ var student = students .hd ;
591
+ if (otherStudents) {
592
+ console .log (student);
593
+ _students = otherStudents;
594
+ continue ;
595
+ }
596
+ console .log (" Last student: " + student);
597
+ return ;
598
+ };
599
+ }
600
+
601
+ printStudents ({
602
+ hd: " Jane" ,
603
+ tl: {
604
+ hd: " Harvey" ,
605
+ tl: {
606
+ hd: " Patrick" ,
607
+ tl: /* [] */ 0
608
+ }
609
+ }
610
+ });
611
+ ```
612
+
613
+ </CodeTab >
614
+
615
+
530
616
### Small Pitfall
531
617
532
618
** Note** : you can only pass literals (i.e. concrete values) as a pattern, not let-binding names or other things. The following doesn't work as expected:
0 commit comments