pattern-matchingocamlincrementref

Counting frequency of char using switches


I am trying to count the amount of time each char appears in a string, I'm using switches and a for loop, however, they are not being incremented properly. Here is my code

let countChar x = 
  match x with
    'A' -> countA := !countA + 1;
  | 'C' -> countC := !countC + 1;
  | 'T' -> countT := !countT + 1;
  | 'G' -> countG := !countG + 1;   
;;

let demoStri = "ACGTACGT" in 
for j = 0 to 7 do
  countChar demoStri.[j];
  let tempA = !countA in
  print_int tempA;
  print_string "\n";
  let tempC = !countC in
  print_int tempC;
  print_string "\n";
  let tempG = !countG in
  print_int tempG;
  print_string "\n";
  let tempT = !countT in 
  print_int tempT;
  print_string "\n";
done

But for some reason it's only incrementing 1, and it returns 1 0 0 0, 2 0 0 0, 3 0 0 0 and so on..... I was wondering if something went wrong in the process?


Solution

  • I see no problem with this code in its current form, it works for me. You don't show your initializations of countA, countC, countT, and countG, but if I initialize as follows:

    let countA = ref 0
    let countC = ref 0
    let countT = ref 0
    let countG = ref 0
    

    Then run your code I get this series of numbers (collapsed four to a line to save space):

    1 0 0 0
    1 1 0 0
    1 1 1 0
    1 1 1 1
    2 1 1 1
    2 2 1 1
    2 2 2 1
    2 2 2 2