Tuesday, January 24, 2012

Dealing with Tuples in Erlang


Say in Python we have a function defined like this:
def foo(**kwargs):
    pass

In languages like Python, we can pass keyword arguments to a function like:
foo(a = 1, b = 2, c = 3, d = 1)



In Erlang the function may look like this:
foo(Args) -> ok.

A call to foo in Erlang would look like:
foo([{a, 1}, {b, 2}, {c, 3}, {d, 1}]).




In Python we could check if 'a' was passed in as a keyword argument with:
return 'a' in kwargs


Whereas in Erlang we need to do:
lists:keyfind('a', 1, Args)

Note that we are looking at the 1st element in our tuple (hence the 1 in the second argument and not a zero).

keyfind returns false if the key was not found, otherwise it returns the tuple




In Python, to find all keys with the value 1 we do:
[k for k, v in kwargs.items() if v == 1]


In Erlang we do:
lists:filter(fun({Key, Value}) -> Value == 1 end, Args).

and just in case you thought that
lists:keyfind(1, 2, Args).
would find all tuples with the second element equal to 1, it only returns the first tuple that it finds.










   


1 comment:

Unknown said...

Do you understand there's a 12 word phrase you can say to your man... that will induce deep feelings of love and instinctual appeal to you deep inside his chest?

That's because deep inside these 12 words is a "secret signal" that fuels a man's impulse to love, idolize and guard you with all his heart...

===> 12 Words Who Trigger A Man's Love Response

This impulse is so hardwired into a man's mind that it will make him work harder than before to make your relationship the best part of both of your lives.

As a matter of fact, fueling this all-powerful impulse is so important to having the best ever relationship with your man that the instance you send your man a "Secret Signal"...

...You'll immediately find him expose his heart and mind for you in a way he haven't experienced before and he'll see you as the one and only woman in the galaxy who has ever truly understood him.