Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does recursion work for active patterns 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 to be an active recognizer, it no longer compiles.

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 was expected to have type char list * 'a but here has type char list

like image 671
yxrkt Avatar asked Mar 19 '23 14:03

yxrkt


1 Answers

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

NOTE: if you want to use active pattern as a function you still can do it:

let rec (|Digits|) = function
    | head::tail when System.Char.IsDigit(head) ->
        let a, b = (|Digits|) tail
        (head::a, b)
    | rest -> ([], rest)
like image 157
desco Avatar answered Mar 26 '23 16:03

desco