Pattern matching on the beginning of a string in f#

后端 未结 3 1342
遥遥无期
遥遥无期 2020-12-23 19:21

I am trying to match the beginning of strings in f#. Not sure if I have to treat them as a list of characters or what. Any suggestions would be appreciated.

Here i

相关标签:
3条回答
  • 2020-12-23 19:32

    You could also use a guard on the pattern:

    match text with
    | txt when txt.StartsWith("The") -> true
    | txt when txt.StartsWith("If") -> true
    | _ -> false
    
    0 讨论(0)
  • 2020-12-23 19:39

    Parameterized active patterns to the rescue!

    let (|Prefix|_|) (p:string) (s:string) =
        if s.StartsWith(p) then
            Some(s.Substring(p.Length))
        else
            None
    
    match "Hello world" with
    | Prefix "The" rest -> printfn "Started with 'The', rest is %s" rest
    | Prefix "Hello" rest -> printfn "Started with 'Hello', rest is %s" rest
    | _ -> printfn "neither"
    
    0 讨论(0)
  • 2020-12-23 19:40

    Yes you have to treat them as a list of characters if you want to use a match expression.

    Simply transform the string with:

    let text = "The brown fox.." |> Seq.toList
    

    Then you can use a match expression but you will have to use chars (the type of elements in the list) for each letter:

    match text with
    | 'T'::'h'::'e'::_ -> true
    | 'I'::'f'::_ -> true
    | _ -> false
    

    As Brian suggest Parameterized Active Patterns are much nicer, there a some useful patterns here (go the end of the page).

    0 讨论(0)
提交回复
热议问题