【问题标题】:How does recursion work for active patterns in F#?递归如何在 F# 中对活动模式起作用?
【发布时间】:2014-08-31 11:20:29
【问题描述】:

我有以下解析整数的函数:

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 但这里有类型 字符列表

【问题讨论】:

    标签: parsing f# metaprogramming


    【解决方案1】:
    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)
    

    【讨论】:

    • 啊,我明白了。我只是在看this。这是有道理的,因为返回类型也是规则的一部分(如果我的术语没有错的话)。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 2018-09-19
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多