How does recursion work for active templates in F #?

I have the following function for parsing an integer:

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

If I change this function as an active recognizer, it will no longer compile.

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: this expression is expected to be of type char list * 'a, but there is a type of char list

+4
source share
1 answer
let rec (|Digits|) = function
    | head::(Digits (a, b)) when System.Char.IsDigit(head) -> (head::a, b)
    | rest -> ([], rest)

Note: if you want to use the active template as a function, you can still do this:

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

All Articles