Scott Nimrod
Scott Nimrod

Reputation: 11595

Do I have to use an explicit match statement to identify its wildcard value?

Do I have to use an explicit match statement to identify its wildcard value?

For example, take the following function:

let (|Positive|Neutral|Negative|) = function
    | x when x > 0 -> Positive
    | x when x = 0 -> Neutral
    | x when x < 0 -> Negative
    | _            -> failwith (sprintf "unknown: %d" _)

Error:

Unexpected symbol '_' in expression

I learned that I can do this without any errors:

let (|Positive|Neutral|Negative|) v =
    match v with
    | x when x > 0 -> Positive
    | x when x = 0 -> Neutral
    | x when x < 0 -> Negative
    | _            -> failwith (sprintf "unknown: %d" v)

UPDATE

Here's the result from a posted answer:

let (|Positive|Neutral|Negative|) = function
    | x when x > 0 -> Positive
    | x when x = 0 -> Neutral
    | x when x < 0 -> Negative
    | x            -> failwith (sprintf "unknown: %d" x)

Upvotes: 0

Views: 58

Answers (1)

kemiller2002
kemiller2002

Reputation: 115488

You can change it to this and it will work:

let (|Positive|Neutral|Negative|) = function
    | x when x > 0 -> Positive
    | x when x = 0 -> Neutral
    | x when x < 0 -> Negative
    | f          -> failwith (sprintf "unknown: %d" f)

Upvotes: 2

Related Questions