F#Pattern元组中的匹配元素

Jas*_*son 0 f#

我试图使用模式匹配测试char类型元组中元素的相等性,如下所示:

let swap (x,y) =
match fst(x,y) with
| snd(x,y) -> (x,y)
| _ -> (y,x);;
Run Code Online (Sandbox Code Playgroud)

并收到以下错误: stdin(11,8): error FS0039: The pattern discriminator 'snd' is not defined

请注意,我已经发现了解决实际问题的更好方法.我只是好奇为什么这种方法不起作用.

Mar*_*zek 5

它不起作用,因为snd(x,y)它不是受支持的模式.你可以在这里看到整个表:模式匹配(F#).

您可以使用变量模式,并在以下后检查相等性when:

match x, y with
| x, y when x = y -> (x,y)
| _ -> (y,x);;
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,最好使用if .. then .. else:

if x = y then (x,y) else (y,x)
Run Code Online (Sandbox Code Playgroud)