in reply to Re: 99 Problems in Perl6
in thread 99 Problems in Perl6

On second thought, the only reason you have a closure here at all is to preserve state between calls. Use a state variable then, and the more normal function definition syntax.

sub compress ($x) { state $previous; if $x ne $previous { return $x; } else { return; } }
Update: I think the if is way too long, but can't remember if there's a context-safe way to return nothing in Perl 6 (that isn't "fail"), to golf out the "return" and say something like return $x ne $previous ?? $x !! $NOTHING_AT_ALL;. In the current application () is probably safe.

Replies are listed 'Best First'.
Re^3: 99 Problems in Perl6
by Ovid (Cardinal) on Dec 15, 2006 at 22:29 UTC

    You know, we're getting pretty close to the terseness of Haskell, but (I think) it's still rather readable:

    my $compress = sub ($x) { state $previous; $x ne $previous ?? $previous = $x !! return; }

    And in Haskell:

    compress :: Eq a => [a] -> [a] compress = map head . group

    Update: as concise, but less "golfy":

    my $compress = sub ($x) { state $previous; return $x ne $previous ?? $previous = $x !! (); }

    Cheers,
    Ovid

    New address of my CGI Course.

      Here's a version of the Perl 6 code that's almost as terse as average Haskell code:

      my $cmp = sub ($x) { state $prv; $x ne $prv ?? $prv = $x !! return; }
      Your Haskell compress unfortunately bottoms out on empty input. It's otherwise much better than the stateful Perl 6 version.

        Lest anyone think I'm a genius, I stole the Haskell code from here.

        Cheers,
        Ovid

        New address of my CGI Course.