在此操作中,我在 RGL 中遇到了别名符号:
mkRoot3 : Str -> Root3 = \fcl -> case fcl of {
f@? + c@? + l => {f = f ; c = c ; l = l} ;
_ => error ("mkRoot3: too short root" ++ fcl)
} ;
它是什么意思,它有什么用?
在此操作中,我在 RGL 中遇到了别名符号:
mkRoot3 : Str -> Root3 = \fcl -> case fcl of {
f@? + c@? + l => {f = f ; c = c ; l = l} ;
_ => error ("mkRoot3: too short root" ++ fcl)
} ;
它是什么意思,它有什么用?
字符 @ 用于模式匹配。该表达式foo@bar
意味着您将某些内容与 regex 匹配bar
,并将结果绑定到 variable foo
。
让我们首先回顾一些在没有@的情况下可以模式匹配字符串的方法:
example1 : Str -> Str = \s -> case s of {
"x" => "the string is exactly x" ;
"x" + _ => "the string starts with x" ;
? => "the string is one character long" ;
? + ? => "the string is two characters long" ;
("a"|"i"|"u") => "the string is a vowel" ;
_ => "whatever, I'm bored"
} ;
在所有这些中,我们没有重用右侧的字符串。如果你想这样做,你可以把它绑定到一个变量中,就像这样——还没有使用 @ ,因为我们只是匹配一个字符串的开始和结束:
example2 : Str -> Str = \s -> case s of {
"x" + rest => "the string starts with x and ends with" ++ rest ;
start + "x" => "the string starts with" ++ start ++ "and ends with x" ;
_ => "..." } ;
最后,如果您想将某些内容与正则表达式匹配并使用与 RHS 上的正则表达式匹配的任何内容,现在您需要使用 @:
example3 : Str -> Str = \s -> case s of {
v@("a"|"i"|"u") => "the string is the vowel" ++ v ;
a@? => "the string is one character long:" ++ a ;
a@? + b@? => "the string is two characters long:" ++ a ++ "followed by" ++ b ;
_ => "..." } ;
如果您只是尝试 matcha + b => …
或任何其他仅包含变量的模式,则它不会匹配正好 2 个字符长的单词。相反,它只会将空字符串与其中一个匹配,将完整字符串与另一个匹配。
因此?
,匹配恰好匹配一个字符的正则表达式,然后将结果绑定到一个变量,是您可以匹配具有精确长度的内容的唯一方法,然后在右侧重用匹配的字符/字符串。
您可以在http://www.grammaticalframework.org/doc/gf-refman.html#pattern-matching阅读更多关于模式匹配的信息。