how to count number of letters with std.algorithm.count / std.algorithm.reduce / std.algorithm.map ?

Simen Kjaeraas simen.kjaras at gmail.com
Fri Nov 16 08:29:12 PST 2012


On 2012-11-16, 16:49, bioinfornatics wrote:

> hi,
>
> I would like to count number of one ore more letter into a string or  
> list of string (string[]) without use a for loop but instead using  
> std.algorithm to compute efficiently.
>
> if you have:
>   string   seq1 = "ACGATCGATCGATCGCGCTAGCTAGCTAG";
>   string[] seq2 = ["ACGATCGATCGATCGCGCTAGCTAGCTAG",  
> "ACGATGACGATCGATGCTAGCTAG"];
>
> i try :
>
> reduce!( (seq) => seq.count("G"), seq.count("C"))(tuple(0LU,0LU),seq1)
>
> and got:
> Error: undefined identifier seq, did you mean import std?
>
> in morre count seem to request a range then to do multiple count into  
> one string it is not easy.
>
> Thanks to show to me how do this

There are several problems here. First, as the compiler is trying to
tell you, the part after the comma is not a valid delegate. It should
look like this:

     reduce!( (seq) => seq.count("G"), (seq) =>  
seq.count("C"))(tuple(0LU,0LU),seq1)

Now, that's not really all that closer to the goal. The parameters to
these delegates (seq) are characters, not arrays of characters. Thus,
seq.count does not do what you want.

Next iteration would be:

     reduce!( (seq) => seq == "G", (seq) => seq == "C" )(tuple, 0LU, 0LU,  
seq1)

Not there yet. seq is an element, "G" is a string - an array. One more:

     reduce!( (seq) => seq == 'G', (seq) => seq == 'G' )(tuple, 0LU, 0LU,  
seq1)

Lastly, reduce expects delegates that take two parameters - the current
value of the accumulator, and the value to be considered:

     reduce!( (acc, seq) => acc + (seq == 'G'), (acc, seq) => acc + (seq ==  
'C') )(tuple(0LU, 0LU), seq1)

There. Now it works, and returns a Tuple!(ulong,ulong)(8, 8).

One thing I think is ugly in my implementation is acc + (seq == 'G'). This
adds a bool and a ulong together. For more points, replace that with
acc + (seq == 'G' ? 1 : 0).

-- 
Simen


More information about the Digitalmars-d-learn mailing list