怎么办模式匹配在Erlang的二进制? [英] How to do pattern matching on a binary in Erlang?

查看:219
本文介绍了怎么办模式匹配在Erlang的二进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我愿做递归在一个二进制文件,并在每次调用从二进制读取多达32位,并在新的二进制返回。但我不能得到匹配的工作,因为我想要的模式。

I would like to do recursion over a binary, and in each call read up to 32 bits from the binary, and return it in a new binary. But I can't get the pattern matching to work as I want.

binaryToBinary(Source) ->
    binaryToBinaryAux(Source, <<>>).

binaryToBinaryAux(<<>>, Target) ->
    Target;
binaryToBinaryAux(<<H:32/binary, T/binary>>, Target) ->
    binaryToBinaryAux(<<T/binary>>, <<Target/binary, H>>).

以下是错误我得到的模式匹配:

Here is the error I get for the pattern matching:

10> mymodule:binaryToBinary(<<"JonasPonas">>).
** exception error: no function clause matching
                    mymodule:binaryToBinaryAux(<<"JonasPonas">>,<<>>) 
                                                          (mymodule.erl, line 51)

我在做什么错用二进制的模式匹配?

What am I doing wrong with the pattern matching of the binary?

推荐答案

模式&LT;&LT; H:32 /二进制,T /二进制&GT;&GT; 匹配含有至少32个字节,分配第一32字节至H二进制和其余字节到T的图案&所述;&所述;&GT;&GT; 匹配的空二进制。这是你唯一的模式。

The pattern <<H:32/binary, T/binary>> matches a binary containing at least 32 bytes, assigning the first 32 bytes to H and the remaining bytes to T. The pattern <<>> matches the empty binary. These are your only patterns.

&LT;&LT;JonasPonas&GT;&GT; 既不是空也不至少有32个字节。因此,它不匹配任何一种你的方式,你会得到你做的错误。

<<"JonasPonas">> is neither empty nor does it have at least 32 bytes. Therefore it does not match either of your patterns and you get the error you do.

要解决此添加处理具有小于32字节(你也可以摆脱空的格局,因为它会接着是多余的)。

To fix this add a pattern that handles binaries that have less than 32 bytes (you can also get rid of the empty pattern as it will then be redundant).

这篇关于怎么办模式匹配在Erlang的二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆