Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant print binary variable

Tags:

elixir

I have a simple variable declared

h = "a"

when I try to to <<h>> I get

> ** (ArgumentError) argument error
>     (stdlib) eval_bits.erl:101: :eval_bits.eval_exp_field1/6
>     (stdlib) eval_bits.erl:92: :eval_bits.eval_field/3
>     (stdlib) eval_bits.erl:68: :eval_bits.expr_grp/4
>     (stdlib) erl_eval.erl:484: :erl_eval.expr/5
>     (iex) lib/iex/evaluator.ex:257: IEx.Evaluator.handle_eval/5
>     (iex) lib/iex/evaluator.ex:237: IEx.Evaluator.do_eval/3

If h holds the value "a" here I can successfully do <<"a">> why is an error for <<h>> then?

like image 235
Yugandhar Chaudhari Avatar asked Dec 13 '22 10:12

Yugandhar Chaudhari


2 Answers

From <<>>/1-types:

When no type is specified, the default is integer:

iex> <<1, 2, 3>>
<<1, 2, 3>>

Elixir also accepts by default the segment to be a literal string or a literal charlist, which are by default expanded to integers:

iex> <<0, "foo">>
<<0, 102, 111, 111>>

Variables or any other type need to be explicitly tagged:

iex> rest = "oo"
iex> <<102, rest>>
** (ArgumentError) argument error

We can solve this by explicitly tagging it as binary:

iex> rest = "oo"
iex> <<102, rest::binary>>
"foo"
like image 122
Adam Millerchip Avatar answered Dec 24 '22 11:12

Adam Millerchip


You can do it but you have to specify that it's a binary:

h = "a"
<<h::binary>>
"a"
like image 25
denis.peplin Avatar answered Dec 24 '22 09:12

denis.peplin