Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string to find first duplicate character - functional vs. prodecural coding style

Tags:

rebol

red

rebol2

I want to parse a string to find the first N duplicate characters found in a (character, n) set.

For example, for "ozzllluu" and sets ("u" => 2), ("d" => 2), ("l" => 3), and ("r" => 3)... I would want to find "lll", because it is 3 characters and happens before the two "u"s.

procedural style solution:

Rebol []

seq-set: [#"u" 2 #"d" 2 #"l" 3 #"r" 3]
str: "ozzllluu"

lastchar: ""
cnt: 1
seq-char: ""

foreach char str [
    either char = lastchar [ 
        cnt: cnt + 1
        if (select seq-set char) = cnt [
            seq-char: char
            break
         ]
   ][
        cnt: 1
   ]
   lastchar: char   
]

either seq-char = "" [
    print "no seq-char"
][
    print join "seq-char " seq-char
]

How would I do this same thing using a parse rule?

In short:

  • parse string for first n duplicate character found in (character ,n) set
  • "function" the existing procedural code
  • dogfood into Rebol / Red!
like image 920
OneArb Avatar asked Dec 15 '22 00:12

OneArb


1 Answers

Here is a solution using Red's Parse (works in R3 too):

seq-set: [2 #"u" | 2 #"d" | 3 #"l" | 3 #"r"]
rule: [any [set char seq-set break | skip]]

red>> parse "ozzllluu" rule
red>> char
== #"l"
like image 64
DocKimbel Avatar answered Jan 14 '23 00:01

DocKimbel