Tuesday, March 3, 2009

F#: The type 'MatchCollection' is not compatible with the type 'seq<'a>'.

I was trying to use regular expressions with sequences, and ran across this problem.
(new Regex ".*").Matches("foo") |> Seq.iter (fun s -> printfn "s is %A" s);;
-----------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
stdin(4,36): error FS0001: The type 'MatchCollection' is not compatible with the type 'seq<'a>'.
> (new Regex "f.*").Matches("foo") |> Seq.cast |> Seq.iter (fun s -> printfn "s is %A" s);;
s is foo
val it : unit = ()
>
Turns out MatchCollection implements System.Collections.IEnumerable, not System.Collections.Generic.IEnumerable<T>. You need to cast it with Seq.cast to use it:
(new Regex "f.*").Matches("foo") |> Seq.cast |> Seq.iter (fun s -> printfn "s is %A" s);;
I got the solution from hubfs - it's a good place for F# information.

No comments: