F#: Pattern Composition?

放肆的年华 提交于 2020-01-01 02:29:27

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/3686199/f-pattern-composition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!