Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# matching with two values

I'm fairly new to F# and I wanted to compare two values with the (match ... with ...) syntax

The problem arises when I attempt to compare two values like this:

let value1 = 19
let isValue1 y =
    match y with
    | value1 -> y + 1
    | _ -> y

I get a warning that the "| _ -> y" portion of the code will never be reached. Why is this?

I know that I can do the following to get the function to work the way I want it to:

let value1 = 19
let isValue1 y =
    match y with
    | _ when y = value1 -> true
    | _ -> false

This works as well

let value1 = 19
let isValue1 y =
    match y with
    | 19 -> true
    | _ -> false

I'm just curious about why I can't do that, and how match actually works.

like image 313
ZeroKelvin Avatar asked Dec 02 '22 08:12

ZeroKelvin


1 Answers

The value1 within the match statement is defined as a new variable, the value of which is set to y (as a match). The value1 you define just above is ignored, just as if you were declaring a local variable in a C# function with the same name as a class variable. For this reason, the first match condition will match everything, not just the previously defined value of value1, hence the error. Hope that clarifies matters.

like image 76
Noldorin Avatar answered Dec 04 '22 15:12

Noldorin