The parse string to search for the first duplicate of the character-functional and produral coding style

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

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

procedural style:

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 can I do the same with a rule parse?

In short:

  • parse a string for the first n repeating character found in (character, n) set
  • "function" existing procedural code
  • dogfood in Rebol / Red!
+4
3

, Red Parse ( R3):

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"
+8

keys:  ["uu" | "dd" | "lll" | "rrr"]
rule: [(k: none)  any [[copy k keys to end ] | skip] ]

>> parse "olllddsslll rr rrr" rule  k
== "lll"
+3

Below the parserule finds all duplicates and skips the others.

;Rebol 2 version
char: charset [#"a" - #"z"]
parse/all "wqooossssccfgg" [some [
    copy x char [copy y some x (print [s: join x y length? s])]
    | skip 
  ]
]
;output
ooo 3
ssss 4
cc 2
gg 2

;Red version
parse "wqooossssccfgg" [some [
    copy x char [copy y some x (print [s: append x y length? s])]
| skip ]]
+1
source

Source: https://habr.com/ru/post/1669163/


All Articles