Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang syntax in function

I have found this code in Ejabberd:

maybe_post_request([$< | _ ] = Data, Host, ClientIp)

I don't understand what [$< | _ ] = Data part do with Data. Could somebody explain?


2 Answers

The construct

[$< | _] = Data

applies a pattern match to Data, expecting it to be a list variable whose first element is the character < and ignoring the rest the elements. Try it in the Erlang shell:

1> Data = "<foo>".
"<foo>"
2> [$<|_] = Data.
"<foo>"

But if Data doesn't match, we get an exception:

3> f(Data), Data = "foo".
"foo"
4> [$<|_] = Data.
** exception error: no match of right hand side value "foo"
like image 159
Steve Vinoski Avatar answered Mar 27 '26 05:03

Steve Vinoski


I don't understand what [$< | _ ] = Data part do with Data. Could somebody explain?

It binds the variable Data to the entire first argument to the function.

The left hand side pattern matches the first argument so that this function clause only matches when the first argument is a string (list) starting with the character <. The variable Data is assigned the entire string fr use in the function body.

like image 32
Vance Shipley Avatar answered Mar 27 '26 05:03

Vance Shipley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!