Mailing List Archive: 49091 messages

[REBOL] Re: count function

From: joel:neely:fedex at: 4-Jul-2001 21:10

```
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