2014-02-18 23 views
1

我剛剛開始OCaml(和函數式編程),我試着編寫一個函數來計算數組(tab)中出現「value」的次數。 我想:OCaml在過濾器上的語法錯誤

let rec count_occ tab value = 
    let rec count_rec idx time = function 
     | tab.length - 1 -> time 
     | _ when tab.(indice) == value-> count_rec (idx + 1) (time + 1) 
     | _ -> count_rec (indice + 1) time 
    in 
    count_rec 0 0 
;; 

不幸的是,它不會因爲語法錯誤的編譯,我沒有找到解決辦法。

回答

3
let rec count_occ tab value = 

上面這個rec​​是沒有必要的。

let rec count_rec idx time = function 
     | tab.length - 1 -> time 

您無法匹配表達式。你想要像下一行那樣使用警衛,或者使用if語句來測試類似的事情。 tab.length也不存在,因爲tabarray,而不是具有length字段的記錄。你想要Array.length tab

真的,雖然你根本不想要functionfunctionfun x -> match x with相同,並且暗示count_rec具有類型int -> int -> int -> int

 | _ when tab.(indice) == value-> count_rec (idx + 1) (time + 1) 

indices未被聲明;讓我們假設你的意思是idx。另外,==是物理上的平等,你真的想要=

 | _ -> count_rec (indice + 1) time 
    in 
    count_rec 0 0 

,你已經開了個好頭,你遞歸的基本原理是正確的,雖然一個邊緣的情況下是不正確的,但你應該能夠解決一個小問題,一旦你有固定的語法問題。

+0

謝謝,我在正確的道路,現在,我的代碼來看:http://pastie.org/8746861但它並沒有真正的工作 – Epitouille

+0

當你使用|匹配idx時您正在創建'idx'到'n'的新綁定,而不是測試'n'的內容是否等於'idx'。相反,這是在警衛中完成的。匹配是結構性的,如分解列表和元組並匹配變體和常量。 – nlucaroni

+0

一旦你解決了這個問題,你應該立即注意到在這種情況下匹配不合適 - 在這三種情況下你都會與'_'匹配。改用if語句。 – nlucaroni

1

finnaly我後我的最終代碼:

let count_occ tab value = 
    let rec count_rec idx time = 
     if (Array.length tab) = idx then 
      time 
     else if (tab.(idx)) = value then 
      count_rec (idx + 1) (time + 1) 
     else 
      count_rec (idx + 1) time 
    in 
    count_rec 0 0 
;; 
+1

看起來不錯! 「tab。(idx)」和「idx = Array.length tab」周圍的額外括號可以爲您節省_precious_ keystrokes;)。 – nlucaroni