Problems with pattern matching in F #

I need help with paternmatching in F #. I want to do this:

            let y x =
            match x with
            | x.Contains("hi") -> "HELLO"
            | x.Contains("hello") -> "HI"
            | x -> x

But that will not work. What's wrong?

+3
source share
3 answers

The easiest way is to use the defense function in your matches.

let y (x:string) =
  match x with
  | x when x.Contains("hi") -> "HELLO"
  | x when x.Contains("hello") -> "HI"
  | x -> x
+7
source

Conditions that include method calls can only be written to whenguard, as pblasucci writes.

If you want to use some of the advanced features of F # (for example, if you need to write a lot), you can define an active template to check for a substring (but don't worry about it if you are just learning F #)

let (|Contains|_|) (what:string) (str:string) = 
  if str.Contains(what) then Some(str) else None

- (, , &):

match "hello world" with
| Contains "hello" (Contains "world" str) -> 
    printfn "%s contains both hello and world!" str
| Contains "hello" str -> 
    printfn "%s contains only hello!" str
| _ -> ()
+7

, , .

, , , , if/then/else:

let y x =
  if x.Contains("hi") then "HELLO"
  elif x.Contains("hello") then "HI"
  else x

Contains, @Tomas Petricek, , , ,

open System.Text.RegularExpressions

///Match the pattern using a cached interpreted Regex
let (|InterpretedMatch|_|) pattern input =
    if input = null then None
    else
        let m = Regex.Match(input, pattern)
        if m.Success then Some [for x in m.Groups -> x]
        else None

///Match the pattern using a cached compiled Regex
let (|CompiledMatch|_|) pattern input =
    if input = null then None
    else
        let m = Regex.Match(input, pattern, RegexOptions.Compiled)
        if m.Success then Some [for x in m.Groups -> x]
        else None

:

let y = function // shorthand for let y x = match x with ...
    | CompiledMatch @"hi" _ -> "HELLO"
    | CompiledMatch @"hello" _ -> "HI"
    | x -> x

, : Contains, StartsWith, EndsWith, Equals :

let y = function
    | CompiledMatch @"^hi$" _ -> "Equals"
    | CompiledMatch @"^hi" _ -> "StartsWith"
    | CompiledMatch @"hi$" _ -> "EndsWith"
    | CompiledMatch @"leadinghiending" _ -> "Beyond"
    | CompiledMatch @"hi" _ -> "Contains"
    | x -> x

(note that the literal lines introduced by @ are not really needed for any of these regular expression examples, but as a rule, I always use them since you need them more often than regular regular expressions).

+5
source

Source: https://habr.com/ru/post/1793512/


All Articles