2017-04-24 78 views
2

未定義名稱空間或模塊'XXXXX'嘗試重新編排合併排序程序時,我在函數中實現了match with語句。函數參數

let rec merge (array : int[]) (chunkA : int[]) (chunkB : int[]) a b i = 
    match a, b with 
    | chunkA.Length, _ -> chunkB 
    | _, chunkB.Length -> chunkA 
    | _ when chunkB.[b] < chunkA.[a] 
     -> array.[i] <- chunkB.[b] 
      merge array chunkA chunkB a (b+1) (i+1) 
    | _ -> array.[i] <- chunkA.[a] 
      merge array chunkA chunkB (a+1) b (i+1) 

但是,Visual Studio中拋出錯誤:

The namespace or module 'chunkA' is not defined. 

這是令人困惑,因爲'chunkA'了函數的參數中指出。

另外,我對F#和函數式編程一般都比較陌生。如果我的代碼中的結構或方法不能滿足要求,那麼請隨時對此進行評論。

另外,如果我很厚,請隨時告訴我。

很多謝謝,盧克

回答

2

當你使用匹配,你需要使用編譯時間常量。

像這樣的東西是你想要

|aa,_ when aa=chunkA.Length -> .... 
3

正如約翰所提到的,你不能直接模式對陣另一個變量的數值。模式的語言只允許常量,構造函數和其他一些東西。

可以使用when寫代碼,但是,你真的不以任何方式match constrct受益,因爲你只需要在when條款的條件。在這種情況下,我會去普通的舊if,因爲它讓你在做更明顯的是什麼:

let rec merge (array : int[]) (chunkA : int[]) (chunkB : int[]) a b i = 
    if a = chunkA.Length then chunkB 
    elif b = chunkB.Length then chunkA 
    elif chunkB.[b] < chunkA.[a] then 
     array.[i] <- chunkB.[b] 
     merge array chunkA chunkB a (b+1) (i+1) 
    else 
     array.[i] <- chunkA.[a] 
     merge array chunkA chunkB (a+1) b (i+1) 

match結構是非常有用的,如果你的模式匹配的功能更強大的數據結構 - 例如如果你在兩個列表(而不是數組)上編寫merge,那麼模式匹配會更好。