2016-09-15 62 views
0

我試圖創建一個函數來總結SML中的一個整數的數字,但我得到以下錯誤。使用SML的整數中的數字總和

Error: operator and operand don't agree [overload conflict] 
    operator domain: real * real 
    operand:   [* ty] * [* ty] 
    in expression: 
    n/(d * 10) 

我試圖將變量轉換爲真實的,但它沒有工作。另外我不明白爲什麼我得到這個錯誤。在SML中不可能使用*和/或int和real等運算符?

的代碼如下:

fun sumDigits (n) = 
    if n < 10 then n 
    else 
    let 
     val d = 10 
    in 
     n mod d + sumDigits(trunc(n/(d*10))) 
    end 

回答

1

看起來你有幾件事情是錯誤的。首先,在分割整數時,你需要使用「div」而不是「/」。 /是爲了實際。另外,trunc是reals的一個函數。第三,你會希望遞歸邏輯只是sumDigits(n div 10),而不是sumDigits(n div(d * 10))。您也可以通過刪除d變量來清理代碼。

fun sumDigits (n) = 
    if n < 10 then n 
    else 
    n mod 10 + sumDigits(n div 10)