开发者

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 bo开发者_JS百科dy patterns.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜