我正在学习f#,目前我正在使用匹配关键字。我正在修改下一个例子,如果数字是2的倍数则打印到屏幕上,它的mod是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
我修改了它并编写了一个额外的匹配:
| x % 2 == 0 -> printfn "it's multiple of 2!"
但这不起作用,它说“%”它是一个未定义的符号......任何想法?谢谢!
答案 0 :(得分:8)
这是一个经典的Tim Toady。其他答案完全正确。我会添加几个变体:
// 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
答案 1 :(得分:7)
您不能将表达式用作match case。保护模式的另一种替代方法是定义active pattern:
let(|Even|Odd|) (x:int) =
if x % 2 = 0 then Even else Odd
然后将其用作普通模式案例
.......
| Even -> printfn "it's multiple of 2!"
.......
答案 2 :(得分:4)
您需要使用guarded pattern rule:
| _ when x % 2 = 0 -> printfn "it's multiple of 2!"