OCAML 使用开关计算字符的频率
OCAML counting frequency of char using switches
我正在尝试计算每个字符在字符串中出现的时间,我正在使用开关和 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,并且它 returns 1 0 0 0、2 0 0 0、3 0 0 0 等等......我想知道是否出了什么问题正在处理中?
这里最大的问题是您使用 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"
我认为此代码的当前形式没有问题,它适用于我。您没有显示 countA
、countC
、countT
和 countG
的初始化,但如果我按如下方式初始化:
let countA = ref 0
let countC = ref 0
let countT = ref 0
let countG = ref 0
然后运行你的代码我得到这一系列数字(折叠四到一行保存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
我正在尝试计算每个字符在字符串中出现的时间,我正在使用开关和 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,并且它 returns 1 0 0 0、2 0 0 0、3 0 0 0 等等......我想知道是否出了什么问题正在处理中?
这里最大的问题是您使用 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"
我认为此代码的当前形式没有问题,它适用于我。您没有显示 countA
、countC
、countT
和 countG
的初始化,但如果我按如下方式初始化:
let countA = ref 0
let countC = ref 0
let countT = ref 0
let countG = ref 0
然后运行你的代码我得到这一系列数字(折叠四到一行保存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