Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: Pattern Composition?

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.

like image 423
zmj Avatar asked Sep 10 '10 15:09

zmj


1 Answers

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!"

like image 120
YotaXP Avatar answered Sep 30 '22 17:09

YotaXP