Last active
October 29, 2022 19:02
-
-
Save nd3i/ebe8f4d2c3ca106e39734d40ade46d03 to your computer and use it in GitHub Desktop.
n-ary function example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
subset Even of Int where * %% 2; | |
sub median { | |
my @n = @_; | |
given @n.elems { | |
when 0 { return () } | |
when Even { return @n.sort[@n/2-1, @n/2].sum/2 } # avg of two middle elements | |
default { return @n.sort[(@n+1)/2-1] } # middle element | |
} | |
} | |
# say median(1, 0); # (0, 1)[0,1].sum/2 => 0.5 | |
# say median(0, 2, 1); # (0, 1, 2)[1] => 1 | |
# say median(); # => () | |
# say median(6, 1, 3, 2, 5, 4); # (1, 2, 3, 4, 5, 6)[2,3].sum/2 => 3.5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment