我试图计算每个字符在字符串中出现的时间,我使用开关和 for 循环,但是,它们没有正确增加。这是我的代码
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
但由于某种原因,它只递增 1,并且返回 1 0 0 0、2 0 0 0、3 0 0 0 等等......我想知道这个过程中是否出了问题?
我认为这段代码当前的形式没有问题,它对我有用。您没有显示
countA
、countC
、countT
和 countG
的初始化,但如果我按如下方式初始化:
let countA = ref 0
let countC = ref 0
let countT = ref 0
let countG = ref 0
然后运行你的代码,我得到这一系列数字(将四个折叠成一行以节省空间):
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
这里最大的问题是您使用
tempH
变量来索引字符串,而不是您应该使用的 j
。
let () =
let demoStri = "ACGTACGT" in
let countA = ref 0 in
let countC = ref 0 in
let countT = ref 0 in
let countG = ref 0 in
for j = 0 to String.length demoStri - 1 do
match demoStri.[j] with
| 'A'-> countA := !countA +1
| 'C'-> countC := !countC +1
| 'T'-> countT := !countT +1
| 'G'-> countG := !countG +1
| _ -> assert false
done;
print_int !countA; print_string "\n";
print_int !countC; print_string "\n";
print_int !countT; print_string "\n";
print_int !countG; print_string "\n"