http://www.perlmonks.org?node_id=638255


in reply to Yet Another Rosetta Code Problem (Perl, Ruby, Python, Haskell, ...)

In JavaScript it's pretty concise, but still understandable:
var arr = "ZBBBCZZ".match(/((.)\2*)/g);
  • Comment on Re: Yet Another Rosetta Code Problem (Perl, Ruby, Python, Haskell, ...)
  • Download Code

Replies are listed 'Best First'.
Re^2: Yet Another Rosetta Code Problem (Perl, Ruby, Python, Haskell, ...)
by erroneousBollock (Curate) on Sep 12, 2007 at 06:13 UTC
    I really like that Javascript version.

    You either like or hate regexps for this kind of thing, but as regexp-based solutions go "ZBBBCZZ".match(/((.)\2*)/g) is damn concise.

    I couldn't get the perl version to be that concise... pity.

    I hope perl6's Rules allow one to specify a sub-match that can be referenced and then thrown away.

    -David

      Earlier in this thread we already had a Perl 6 solution resembling this:
      "ZBBBCZZ".comb(/(.)$0*/)
      I think that does what you want here, though in this case it's the .comb method that's forgetting the $0 capture, not the regex, so you raise an interesting point for the general case.

      It's not specced yet, but the current standard grammar has two rules called "same" and "differ" that could be used for this, along with the "quantify via separator" form:

      "ZBBBCZZ" ~~ m:g/ . ** <?same> /)
      Though that is also kinda cheating on your general point by not capturing anything in the first place...

      At the moment, forgetting a capture within Perl 6 regex involves forcefully rebinding the capture to nothing, or returning an alternate result via a closure. Perhaps there should be a way to declare temp bindings that are not intended for the final match. But maybe not, if it's just going to turn into an obscure feature. So more likely it'll be some kind of context that just happens to work that way when you expect it to, like .comb does, only inside regex syntax.

      I couldn't get that javascript version to work. Sure, it looks nice. It looks very much like something many tried as a first stab in Perl. But I'm not convinced it works in javascript any better than it works in Perl. I was not able to get it to return anything (while in Perl it returns too much).

      Update: Thanks, eB. I was eventually able to get your example to demonstrate that the code works.

      - tye        

        It works just fine. Try pasting the following into your url bar:

           javascript:alert("ZBBBCZZ".match(/((.)\2*)/g))

        That should alert the output of .toString() called on the array result.
        If you have Firefox use the following to see the unadulterated array source:

           javascript:alert(("ZBBBCZZ".match(/((.)\2*)/g)).toSource())

        -David

        Update: Does that imply that Javascript has different capture semantics than perl?