F#: Pattern Composition?

前端 未结 1 1996
甜味超标
甜味超标 2021-02-08 03:56

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

1条回答
  •  后悔当初
    2021-02-08 04:03

    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 讨论(0)
提交回复
热议问题