且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Erlang:变量未绑定

更新时间:2021-12-31 00:44:48

模式匹配的规则是,如果变量X出现在两个子模式中,例如{X,X},或者{X,[X]}或类似的字符,则它们在两个位置必须具有相同的值,但每个子模式的匹配仍在相同的输入环境中完成-一侧的绑定不会转移到另一侧。相等性检查将在概念上完成,就像您在{X,X2}上进行了匹配并添加了保护X =:= X2一样。这意味着即使没有将元组中的Length字段设为最左侧的元素,也不能将其用作二进制模式的输入。

The rules for pattern matching are that if a variable X occurs in two subpatterns, as in {X, X}, or {X, [X]}, or similar, then they have to have the same value in both positions, but the matching of each subpattern is still done in the same input environment - bindings from one side do not carry over to the other. The equality check is conceptually done afterwards, as if you had matched on {X, X2} and added a guard X =:= X2. This means that your Length field in the tuple cannot be used as input to the binary pattern, not even if you make it the leftmost element.

但是,是二进制模式,绑定在字段中的变量可以从左到右在其后的其他字段中使用。因此,以下工作(在二进制文件中使用前导32位大小的字段):

However, within a binary pattern, variables bound in a field can be used in other fields following it, left-to-right. Therefore, the following works (using a leading 32-bit size field in the binary):

1> <<Length:32, A:Length/binary, Rest/binary>> = <<0,0,0,3,1,2,3,4,5>>.
<<0,0,0,3,1,2,3,4,5>>
2> A.
<<1,2,3>>
3> Rest.                                                               
<<4,5>>