Question

I'm learning f# and currently I'm with the match keyword. I'm modifying the next example, to print into the screen if a numbers is multiple of 2, it's mod is 0.

[<Literal>]
let Three = 3

let filter123 x =
match x with 
// The following line contains literal patterns combined with an OR pattern.
| 1 | 2 | Three -> printfn "Found 1, 2, or 3!" 
// The following line contains a variable pattern.
| var1 -> printfn "%d" var1

for x in 1..10 do filter123 x

I have modified it and coded an additional match for:

| x % 2 == 0 -> printfn "it's multiple of 2!"

But that doesn't work, it says that "%" it's an undefined symbol... any ideas? Thanks!

Was it helpful?

Solution

This is a classic Tim Toady. The other answers are perfectly correct. I would add a couple of variations:

// Eugene's answer
let filterEven1 x =
    match x with
    | _ when x % 2 = 0 -> printfn "%d is even!" x
    | _ -> printfn "%d is not even" x

// equivalent to above, but with "function" match syntax
let filterEven2 = function
    | x when x % 2 = 0 -> printfn "%d is even!" x
    | x -> printfn "%d is not even" x

// variation on Gene's answer
let (|Even|Odd|) x =
    if x % 2 = 0 then Even(x) else Odd(x)

let filterEven3 = function
    | Even(x) -> printfn "%d is even!" x
    | Odd(x) -> printfn "%d is not even" x

// probably how I would do it
let filterEven4 x =
    match x % 2 with
    | 0 -> printfn "%d is even!" x
    | _ -> printfn "%d is not even" x

OTHER TIPS

You cannot use an expression as a match case. Another alternative to a guarded pattern would be defining an active pattern:

let(|Even|Odd|) (x:int) =
    if x % 2 = 0 then Even else Odd

and then using it as a normal pattern case

.......
| Even -> printfn "it's multiple of 2!"
.......

You need to use guarded pattern rule:

| _ when x % 2 = 0 -> printfn "it's multiple of 2!"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top