alpaca-lang / alpaca

Functional programming inspired by ML for the Erlang VM
Other
1.44k stars 47 forks source link

Add support for dynamic size in binary pattern matching #211

Open cmkarlsson opened 7 years ago

cmkarlsson commented 7 years ago

I often have the need to pattern match binaries on dynamic sizes. Currently this is not possible in alpaca (which gives {invalid_bin_qualifier,<<"s">>})

An example:

let s = 5 in
match bin with
   <<x: type=binary unit=8 size=s, rest: type=binary>>

I think it would make sense to have the size being expressed as any expression returning an integer.

Tested with alpaca 620b9fa134cc68e7342b29bcdb4baf6e5482e1f3

NobbZ commented 7 years ago

As far as I know, this is not possible in the BEAM.

Binary sizes for everything but the "tail" has to be known at compiletime.

utkarshkukreti commented 7 years ago

This is definitely possible in the BEAM. Elixir:

iex(1)> s = 5
5
iex(2)> <<x::binary-size(s), rest::binary>> = "foobarbaz"
"foobarbaz"
iex(3)> x
"fooba"
iex(4)> rest
"rbaz"
NobbZ commented 7 years ago

Oh, either I missed a change in the BEAM or I am missremembering some details around this...

utkarshkukreti commented 7 years ago

BEAM does not support having a variable length for any chunk except the last even if it can be easily calculated manually by subtracting the size of the binary and the size of the last chunk. You may be misremembering that.

iex(5)> <<x::binary, rest::binary-size(2)>> = "foobarbaz"
** (CompileError) iex:5: a binary field without size is only allowed at the end of a binary pattern and never allowed in binary generators