Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching with string in Erlang. Variable in left position

With Erlang I can do something like this:

"kapa" ++ D = "kapagama". % D now has a value "gama"

Is there a way to put the "variable" in left position? Something like

D ++ "gama" = "anyLengthStringgama".

For this expression shell returns an error:

* 1: illegal pattern

Bonus question: Can somebody explain why it doesn't work? What is the logic behind it?

like image 312
kharandziuk Avatar asked Jun 29 '15 17:06

kharandziuk


1 Answers

"kapa" ++ D = "kapagama".

is just syntactic sugar for

[$k, $a, $p, $a | D] = "kapagama".

and this is just syntactic sugar for

[$k|[$a|[$p|[$a|D]]]] = "kapagama".

There is not any counterpart for this code:

D ++ "gama" = "kapagama".

which this can be syntactic sugar for. So as Steve Vinoski wrote, you have to do use lists:reverse/1

"amag" ++ D = lists:reverse("kapagama"), lists:reverse(D).

or use re module.

like image 172
Hynek -Pichi- Vychodil Avatar answered Sep 19 '22 17:09

Hynek -Pichi- Vychodil