Hacker News new | past | comments | ask | show | jobs | submit login

As an example, here's my quick implementation of the original code in Perl 6. (Note that this is the entire implementation, no helper functions needed.)

    sub GetSlots($slots, $max) 
    { 
        my @a = (1..($max-1)).pick($slots-1, :repl).sort;
        return (@a, $max) >>-<< (0, @a);
     } 
(1..($max-1)) generates a list of integers from 1 to $max - 1. pick($slots-1, :repl) randomly picks $slots - 1 from the first list, replacing the one picked each time (so duplicates are possible). sort does just what you would think.

The second line of the sub uses a hyper-operator to subtract one array from another -- in this case the sorted array of random numbers plus $max on the left, 0 plus the array on the right. The result is also an array, and that's what we return.

It's not a pure functional implementation, obviously -- you could certainly do that in Perl 6, but to my mind this approach emphasizes what is actually going on, rather than hiding it in the Pairwise function. (Without digging into the Pairwise function code, how do you know if it splits (1,2,3,4) into (1,2) and (3,4) or (1,2), (2,3), and (3,4)?)

BTW, this code already works in the Rakudo implementation of Perl 6...




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: