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

count



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



Follow-Ups: