views:

194

answers:

3

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.

+6  A: 

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.

Noldorin
+4  A: 

Pattern-matching is both a control construct (what code executes next) and a binding construct (like 'let', bind a name to a value). So when you do

match expr with
| name -> ...

the pattern ("name") always matches and the identifier 'name' just gets bound to the value of the expression. This is why pattern-matching is mostly used with discriminated unions (case types), where you match based on the structure. E.g.

match someOption with
| Some(x) -> ... // binds x
| None -> ...

match someList with
| h :: t -> ... // binds h and t to head/tail
| [] -> ...
Brian
+1  A: 

You can just match the Input to Literals/Identifiers marked by the [<Literal>] Attribute without binding it.

For Example:

#light
[<Literal>]
let E  = 2.718281828459


let isE x =
    match x with
    | E -> true
    | _ -> false

print_any (isE 3.2)
print_any (isE E)

According to Crish Smith

David Klein