[Prev][Next][Index][Thread]

Re: count



I like the reduce version, but reduce1 will fail with
empty collections. Here is my try:

define function count(sequence :: <sequence>, element,
#key test = \=) => matches :: <integer>;
  reduce(0, method(sofar :: <integer>, elem)
test(elem, element) & sofar + 1 | sofar end,
sequence);
end function count;

// untested!

There is still some problem with the argument order
passed to test, but I guess the above is sensible as
most comparisons don't care (symmetric) and the it
would work with
	count(seq, <integer>, test: instance?)
just as \select does.

We could put this in coll-ext library. Maybe there is
something like it already.

	Gabor

--- Bruce Hoult <bruce@hoult.org> wrote:
> Is there any particular reason that Dylan doesn't
> have a "count()" 
> function built-in?
> 
> Of course it's easy to do yourself -- including
> synthesising it 
> functionally from other operations -- but at a cost
> in efficiency.  And 
> it's a common enough thing that other competitor
> languages such as 
> Common Lisp and Python have it built in.
> 
> The signature should probably be something like:
> 
> define method count(sequence, element, #key test =
> \=)
>     => (count :: <integer>)
> 
> 
> Examples of how you can do it using existing
> primitives include:
> 
>   choose(curry(test, element), sequence).size
> 
>   reduce1(\+, map(method(e) if(test(element, e)) 1
> else 0 end, sequence)
> 
> 
> The better way would be to rewrite choose()
> slightly:
> 
>   for (t = 0 then if (test(element, e)) t + 1 else t
> end,
>        e in sequence)
>   finally
>     t;
>   end for;
> 
> 
> What do y'all think?
> 
> -- Bruce
> 
> 
> 


__________________________________________________
Do You Yahoo!?
Get email at your own domain with Yahoo! Mail. 
http://personal.mail.yahoo.com/


Follow-Ups: References: