F # Pattern matching with argument

This is probably simple, but can anyone explain why the following pattern matching is unreasonable? It specifies other rules, for example. 1, 0, _ will never match.

let matchTest(n : int) = 
    let ran = new Random()
    let i = ran.Next(0, 2)
    match i with
    | n -> printfn "%i" n
    | 1 -> printfn "1"
    | 0 -> printfn "0"
    | _ -> printfn "impossible"

The same for this:

let matchTest(n : int) = 
    let ran = new Random()
    let i = ran.Next(0, 2)
    let m = n
    match i with
    | m -> printfn "%i" m
    | 1 -> printfn "1"
    | 0 -> printfn "0"
    | _ -> printfn "impossible"

So why can't it match nor mright here?

+4
source share
3 answers

nin the first example, it is a place symbol that is filled if the match is successful. This is the same as the entry:

let matchTest(n : int) = 
    let ran = new Random()
    let i = ran.Next(0, 2)
    match i with
    | x -> printfn "%i" x
    | 1 -> printfn "1"
    | 0 -> printfn "0"
    | _ -> printfn "impossible"

x i, , ->. , , .

, n, , .

. , , n, n .

, shadowing.

:

let foo n =
    let n = 1
    n

:

> foo 42;;
val it : int = 1
> foo 1337;;
val it : int = 1

, let-bound n n.

OP, n, , .

+6

| m -> 

m, . , m in

let m = n 

m, .

, , .

, . guard

| m when m = n ->
+3

, , , :

let matchTest(n : int) = 
    let ran = new Random()
    ran.Next(0, 2)
    |> function
       | n -> printfn "%i" n
       | 1 -> printfn "1"
       | 0 -> printfn "0"
       | _ -> printfn "impossible"

, ( ) , , . () n .

| pattern ->

" " / (.. ) NOT, , .

Then you need to apply the guard clause for this "newly created variable":

| pattern when pattern = n -> printfn "%i" n

See also https://msdn.microsoft.com/en-us/library/dd233242.aspx

Or comprehensive explanations with examples and the fact that you never knew what you should study (in the best sense!) At http://fsharpforfunandprofit.com/posts/match-expression/

And yes, matching expressions can be confusing at first. That was for me, at least.

+3
source

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


All Articles