user1040323
user1040323

Reputation: 501

Use a value bound to an identifier in f# pattern?

I want a recursive function in F# with a signature of: string * int * char -> int, One terminating pattern is an empty string | ("", i, c) -> 0, A second should be i = String.length s {when s is the first item in the triple}

    let rec myf (s, i, c) =
      let lens = String.length s in
         match s, i, c with
         | "", i,   c -> 0
         | s, lens, c -> 0
         | s, i,    c -> (if s.[i] = c then 1 else 0) + myf(s, i+1, c)

This does not work because the 3rd pattern is never matched, presumably because lens in the 2nd pattern is treated as a wildcard. Is it possible to use a symbol with a value bound to it in a pattern, with a pattern matching against only that value?

PS: myf counts the occurrences of c in s at an index >= i

Upvotes: 2

Views: 91

Answers (1)

Lee
Lee

Reputation: 144136

You need to add a guard:

let rec myf (s, i, c) =
    match s, i, c with
    | "", i,   c -> 0
    | s, i, c when s.Length = i -> 0
    | s, i,    c -> (if s.[i] = c then 1 else 0) + myf(s, i+1, c)

Upvotes: 4

Related Questions