add perl6 code for chapters 1-4 (#49)

This commit is contained in:
ryn1x
2018-01-04 07:46:31 -07:00
committed by Aditya Bhargava
parent dd0100e471
commit 7d48d29139
11 changed files with 194 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
#!/usr/bin/env perl6
use v6.c;
sub sum(@arr) {
my $total = 0;
for @arr {
$total += $_;
}
return $total;
}
my @arr = 1, 2, 3, 4;
say sum(@arr);

View File

@@ -0,0 +1,8 @@
#!/usr/bin/env perl6
use v6.c;
multi sum([]) { 0 };
multi sum(@arr) { @arr[0] + sum(@arr[1..*]) }
my @arr = 1,2,3,4,5;
say sum(@arr);

View File

@@ -0,0 +1,8 @@
#!/usr/bin/env perl6
use v6.c;
multi count([]) { 0 }
multi count(@arr) { 1 + count(@arr[1..*]) }
my @arr = 1,2,3,4,5;
say count(@arr);

View File

@@ -0,0 +1,11 @@
#!/usr/bin/env perl6
use v6.c;
sub my-max(@arr) {
if @arr.elems == 2 { return (@arr[0] > @arr[1]) ?? @arr[0] !! @arr[1] }
my $sub-max = my-max(@arr[1..*]);
return (@arr[0] > $sub-max) ?? @arr[0] !! $sub-max;
}
my @arr = 1,2,3,4,5;
say my-max(@arr);

View File

@@ -0,0 +1,21 @@
#!/usr/bin/env perl6
use v6.c;
sub quicksort(@arr) {
if @arr.elems < 2 {
# base case, arrays with 0 or 1 element are already "sorted"
return @arr;
}
else {
# recursive case
my $pivot = @arr[0];
# sub-array of all the elements less than the pivot
my @less = (gather for @arr[1..*] { take $_ if $_ <= $pivot });
# sub-array of all the elements greater than the pivot
my @greater = (gather for @arr[1..*] { take $_ if $_ > $pivot });
return (|quicksort(@less), $pivot, |quicksort(@greater));
}
}
my @arr = 10, 5, 2, 3;
say quicksort(@arr);