OCAML使用开关计算char的频率

时间:2016-10-17 00:57:29

标签: switch-statement ocaml increment ref

我正在尝试计算每个字符串在字符串中出现的时间,我使用开关和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等等......我想知道是否出现了问题过程

2 个答案:

答案 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"

答案 1 :(得分:0)

我认为此代码的当前形式没有问题,它对我有用。您没有显示countAcountCcountTcountG的初始化,但如果我初始化如下:

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