I'm trying to write a pattern that composes two other patterns, but I'm not sure how to go about it. My input is a list of strings (a document); I have a pattern that matches the document header and a pattern that matches the document body. This pattern should match the entire document and return the results of the header and body patterns.
+7
A:
You can run two patterns together using &
. You left out some details in your question, so here's some code that I'm assuming is somewhat similar to what you are doing.
let (|Header|_|) (input:string) =
if input.Length > 0 then
Some <| Header (input.[0])
else
None
let (|Body|_|) (input:string) =
if input.Length > 0 then
Some <| Body (input.[1..])
else
None
The first pattern will grab the first character of a string, and the second will return everything but the first character. The following code demonstrates how to use them together.
match "Hello!" with
| Header h & Body b -> printfn "FOUND: %A and %A" h b
| _ -> ()
This prints out: FOUND: 'H' and "ello!"
YotaXP
2010-09-10 16:49:50
+1 Learned something new!
Dario
2010-09-12 17:31:59