2014-02-17 63 views
3

我試圖建立列表最小值出現的索引列表。在OCaml中輸入錯誤

let rec max_index l = 
let rec helper inList min builtList index = 
match inList with 
| [] -> builtList 
| x :: xs -> 
    if (x < min) then 
     helper xs x index :: builtList index + 1 //line 63 
    else 
     helper xs min builtList index + 1 
in helper l 100000 [] 0;; 

它給我下面的錯誤線路63

Error: This expression has type 'a list -> 'a list 
     but an expression was expected of type 'a 
     The type variable 'a occurs inside 'a list -> 'a list 

預計類型的「A的表達?我不確定它爲什麼這麼說。我的猜測是它有事情做與index::builtList

回答

5
 helper xs x index :: builtList index + 1 //line 63 
    else 
     helper xs x index min index + 1 

您遇到的問題是,你要非列表傳遞到第65行(min)你的助手功能,同時試圖通過將int list設置爲63行上的相同參數。嘗試用[min]min::[]替換min

編輯:

更新後,出現的問題是函數調用是左關聯的優先級高於二元運算符(見here),所以helper xs x indexindex :: builtList前執行,同樣helper xs x index :: builtListindex + 1之前執行。爲了獲得評估的正確順序,你需要把括號周圍的其他函數調用即::+加上它們的參數是這樣的:

 helper xs x (index :: builtList) (index + 1) //line 63 
    else 
     helper xs x index min (index + 1) 
+0

我其實誤以爲這兩行。我已經更新了它。同樣的錯誤,雖然 – user2079802

+0

我希望你能幫助的另一件事..你知道如何使它更安全/多態嗎?現在,當我運行它時,我得到'這個表達式的類型爲float,但是表達式期望爲int類型 - 行62 – user2079802

+0

@ user2079802你得到那個if(x mydogisbox

2

你需要一些括號。函數調用綁定比二元運算符更緊密。所以

if (x < min) then 
    helper xs x (index :: builtList) (index + 1) 
else 
    helper xs min builtList (index + 1)