2014-08-31 97 views
4

我有解析整數以下功能:遞歸如何爲F#中的活動模式工作?

let rec digits = function 
    | head::tail when System.Char.IsDigit(head) -> 
     let result = digits tail 
     (head::(fst result), snd result) 
    | rest -> ([], rest) 

如果我改變了功能,是一個積極的識別器,它不再編譯。

let rec (|Digits|) = function 
    | head::tail when System.Char.IsDigit(head) -> 
     let result = Digits tail 
     (head::(fst result), snd result) 
     //   ^^^^^^  ^^^^^^ see error* 
    | rest -> ([], rest) 

*錯誤FS0001:此表達預計將有char類型列表*「一但這裏的類型爲 焦炭列表

回答

7
let rec (|Digits|) = function 
    | head::(Digits (a, b)) when System.Char.IsDigit(head) -> (head::a, b) 
    | rest -> ([], rest) 

注: 如果你想使用活動模式作爲一個功能,你仍然可以做到這一點:

let rec (|Digits|) = function 
    | head::tail when System.Char.IsDigit(head) -> 
     let a, b = (|Digits|) tail 
     (head::a, b) 
    | rest -> ([], rest) 
+0

啊,我明白了。我只是看着[這個](http://en.wikibooks.org/wiki/F_Sharp_Programming/Active_Patterns#Parameterizing_Active_Patterns)。這是有道理的,因爲返回類型也是規則的一部分(如果我的術語沒有錯的話)。非常感謝! – yxrkt 2014-08-31 08:10:38