in reply to Re^2: Functional shuffle
in thread Functional shuffle

A functional splice, though, shouldn't have side-effects.
Then use a slice instead. No, that's not Perl keyword, instead, it's a pattern you implement using array indexes.

Since we need the same random index more than once, I stuff it into a temporary variable. I don't think you consider those very "functional", but what the heck...

sub quite_functional_FY { my $i = int rand @_; return @_ ? ($_[$i], quite_functional_FY(@_[0 .. $i-1, $i+1 .. $#_ +])) : (); }

I think you can get a faster implementation by avoiding the recursion for lists that don't need shuffling: lists of one item (or less: 0).

sub quite_functional_FY { my $i = int rand @_; return @_ > 1 ? ($_[$i], quite_functional_FY(@_[0 .. $i-1, $i+1 .. + $#_])) : @_; }

Replies are listed 'Best First'.
Re^4: Functional shuffle
by tlm (Prior) on Apr 02, 2005 at 16:11 UTC

    Yes, of course. What was I thinking? This is almost twice as fast as the "cut" approach I proposed, and clearer to boot. Ode to bart

    the lowliest monk

Re^4: Functional shuffle
by Roy Johnson (Monsignor) on Apr 04, 2005 at 14:01 UTC
    I think I'd gotten stuck in the mindset that functional programming requires streams, but there's no reason you couldn't use slices. Variables are not strictly functional, per se, but it's trivial to have an auxiliary function that does the same thing, so I don't object to them.

    I see there's some confusion about what qualifies as functional. That's probably my fault for not specifying. I punted, because I don't think I had it well-defined in my own mind. But I think I have a better idea now:

    In the purest sense, a functional program is one in which nothing is modified — all new values are modified copies of something else. In keeping with that, the only variables are parameters to the functions.

    Most functional languages allow for some practical exceptions to avoid cumbersome jumping through hoops, as in the case of your temp variable. I like your solution a lot.


    Caution: Contents may have been coded under pressure.