Erlang Thursday – lists:member/2

To go with this weeks Ruby Tuesday post about Enumerable#include?, I decided I would highlight Erlang’s counterpart, lists:member/2.

Sidebar for those unfamiliar with Erlang: lists:member/2 is read as the function member with arity 2, which is found in the lists module. Arity being the number of arguments that the function takes. The module is important, because modules are the containers in which all functions must live — primarily because modules are the unit of code reloading in Erlang — but that way you know which specific member function is being referred to.

All that being said, the function member, in the lists module, takes two arguments: the item being looked for which is an Erlang term, and the list of Erlang terms to check; and returns true if the term is found in the list. An Erlang term is just a piece of data which can be of any of the Erlang data types.

For ability to try this out, the expression is normal, and the return value is the line that starts with the % symbol, which is the Erlang comment, to allow for copy and pasting into the Erlang shell erl.

It can be something as simple for checking if a number is in a list of numbers:

lists:member(4, [1, 2, 3, 5, 8, 13, 21]).
% false
lists:member(13, [1, 2, 3, 5, 8, 13, 21]).
% true

or if an atom is in a list of atoms:

lists:member(c, [a, b, c, d]).   
% true
lists:member(q, [a, b, c, d]).   
% false

or list of more complex terms such as a tuple, or tuples with lists inside them:

lists:member({d, 4}, [{a, 1}, {b, 2}, {c, 3}, {d, 4}]).
% true
lists:member({'Foo', [bar, baz]}, [a, 1, {'Foo', [bar, baz]}]). 
% true
lists:member({fu, [bar, baz]}, [a, 1, {'Foo', [bar, baz]}]).    
% false

or even an integer, or “character”, in a string:

lists:member($a, "banana").
% true
lists:member(97, "banana").
% true
lists:member($A, "banana").
% false

Which if you look carefully enough, you might be able to get the hint that a string in Erlang is really just a list of integers.

Hope this is an interesting comparison between Ruby and Erlang, and my give you some insight into Erlang if you are unfamiliar with the language.

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *