2017-10-09 37 views
2

我开始学习OCaml语言。你能告诉我为什么这段代码显示错误吗?OCaml:为什么我得到这个错误?

let unite x = 
    if x < 100 then x mod 10 
    else if x >= 100 then x mod 100;; 

let dizaine x = 
    if x < 100 then x/10 
    else if x >= 10 then unite(x/10);; 

let centaine x = 
    if x >= 100 then x/100;; 


let somme_chiffre x = 
    if x >= 100 then unite x + dizaine x + centaine x 
    else if x > 9 then unite x + dizaine x 
    else unite x;; 

let div3 x = if ((somme_chiffre x) mod 3) = 0 then 1 else 0;; 

print_int(div3 32);; 
print_string("\n");; 

的错误是:文件 “./test.ml”,第3行,字符24-33: 错误:此表达式具有int类型但预期类型 单元

+1

提示:我为Reason项目提出了一个问题,试图改善这个错误,因为坦率地说,这种情况的错误信息是绝对可怕的。如果错误得到改善,它会首先触发Reason/BuckleScript,但是希望整个错误改进项目最终会被OCaml正确地应用。无论如何,请参阅https://github.com/reasonml-community/error-message-improvement/issues/30 – glennsl

回答

4
的表达

unite函数中最后的if没有else部分。您需要int类型的else部分以匹配该函数的其余部分。或者,由于您的两项测试是详尽且互相排斥的,您实际上可以不用第二个if。这将是一个更加整洁的解决方案。

if x < 5 then 
    (* x is less than 5 in this branch *) 
else 
    (* x is >= 5 in this branch *) 
+0

谢谢,这是问题所在! – Skysork

+0

@Skysork你能接受这个答案吗? – PieOhPah

相关问题