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

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.

Replies are listed 'Best First'.
Re^4: 99 Problems in Perl6
by chromatic (Archbishop) on Dec 16, 2006 at 00:06 UTC

    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; }
Re^4: 99 Problems in Perl6
by gaal (Parson) on Dec 15, 2006 at 22:39 UTC
    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.

        The "alternative solution" posted there doesn't suffer from the monomorphism restriction*, and thus does less to propagate the myth that one has to be a genius to write code in Haskell. It also works correctly with empty input :-)

        compress [] = [] compress [a] = [a] -- singleton list compress (x:y:xs) = (if x == y then [] else [x]) ++ compress (y:xs)
        *Something that, for the casual programmer, is quite technical but uninteresting, has a scary name, and a not-that-friendly error message.