[REBOL] Re: count function
From: jelinem1:nationwide at: 5-Jul-2001 9:12
It also depends on how you want to count:
>> count "ABABABABABAABABABABABABABABABABA" "ABA"
== 8
- OR -
>> count "ABABABABABAABABABABABABABABABABA" "ABA"
== 15
- Michael Jelinek
From: Joel Neely <[joel--neely--fedex--com]>@inet01.prod.fedex.com on
07/04/2001 09:10 PM
Please respond to [rebol-list--rebol--com]
Sent by: [jn--inet01--prod--fedex--com]
To: [rebol-list--rebol--com]
cc:
Subject: [REBOL] Re: count function
Hi, Christian and Maksa,
Just a couple of additional remarks...
Christian Langreiter wrote:
> count: func [x y /local n] [
> n: 0
> while [not = none find x y] [
> n: n + 1
> x: next find x y
> ]
> n
> ]
>
If you don't mind a tiny bit of refactoring, I'd offer
count: func [x y /local n] [
n: 0
while [found? x: find x y] [
n: n + 1
x: next x
]
n
]
based on the transformation
not = none foo -> not none? foo -> found? foo
and eliminating the redundant invocations of FIND, since
after passing the test of
found? find x y
the subsequent
x: next find x y
would FIND exactly the same occurrence.
>> count [a b c a z z] 'a
== 2
>> count "boomboxxbox" "box"
== 2
>> count [Joe Jane Joe Simon] 'Joe
== 2
>> count "ABCSOMESTUFFABDMOREABSTUFFANDTHENABESOME" "AB"
== 4
> >
> > Any suggestions what would the cleanest and most
> > "Rebolesque" possible 'count' function look like?
> > Returning something like this:
> >
> > >> count [Joe Jane Joe Simon] Joe
> > >> 2
> >
The quoting of JOE into a LIT-WORD! value, as Christian
showed with his reply, is probably necessary.
>> count [Joe Jane Joe Simon] Joe
** Script Error: Joe has no value
** Near: count [Joe Jane Joe Simon] Joe
In the expression
count [Joe Jane Joe Simon] Joe
the two arguments are a block of (unevaluated) words and
a word (possibly evaluated, depending on the definition
of the function).
In order for the above to succeed (with non-zero result!)
1) COUNT must defined to allow a WORD! as second argument,
as in
count: func [x 'y /local n] [
n: 0
while [found? x: find x y] [n: n + 1 x: next x]
n
]
>> count "ABCSOMESTUFFABDMOREABSTUFFANDTHENABESOME" "AB"
== 4
>> count [Joe Jane Joe Simon] 'Joe
== 2
>> count [Joe Jane Joe Simon] Joe
== 2
>> count [a b c a z z] 'a
== 2
but then we have trouble with the (presumably common)
case of
>> Somebody: 'Joe
== Joe
>> count [Joe Jane Joe Simon] Somebody
== 0
2) The even more unlikely case (given the original argument
handling) of
>> Joe: 'Joe
== Joe
>> count [Joe Jane Joe Simon] Joe
== 2
which, I must admit, I've never had occasion to do! ;-)
-jn-
------------------------------------------------------------
Programming languages: compact, powerful, simple ...
Pick any two!
joel'dot'neely'at'fedex'dot'com