F#中的主动模式递归是如何工作的?

4

下面是我用于解析整数的函数:

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)

*error FS0001: 预期此表达式类型为 char list * 'a 但实际类型为 char list。
1个回答

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)

啊,我明白了。我刚在看这个:链接。考虑到返回类型也是规则的一部分(如果我的术语没有错的话),这很有道理。非常感谢! - yxrkt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接