Eddy
Eddy

Reputation: 11

Erlang: How do you return an element of a list?

For example: [{a,b},{c,d},{e,f}]. I want to pick on the list with an argument (being c) and it will return d.

Upvotes: 1

Views: 290

Answers (3)

vkatsuba
vkatsuba

Reputation: 1459

You can use few approaches or use Erlang functions from the standard library(like lists etc.) or you can create your own, eg:

List Comprehensions

1> List = [{a,b}, {c,d}, {e,f}].
2> Being = e.
3> [Result] = [Y || {X, Y} <- List, Being =:= X].
4> Result.
f

Functions

1> GetVal = fun GetVal (_, [])                -> not_found;
                GetVal (X, [{X, Result} | _]) -> Result; 
                GetVal (X, [_ | T])           -> GetVal(X, T)
            end.
2> List = [{a,b}, {c,d}, {e,f}].
3> Being = e.
4> GetVal(Being, List).
f

The simple way to use Pattern Matching and List Handling.

Upvotes: 3

Brujo Benavides
Brujo Benavides

Reputation: 1958

If you don't mind using functions from the standard library, you can use lists:keyfind/2 or proplists:get_value/2,3.

Upvotes: 1

7stud
7stud

Reputation: 48599

  1. Write a program that prints each tuple in the list.

  2. Write a program that prints just the second element of each tuple in the list.

  3. Write a program that takes an argument Target along with a List. When you find the tuple {Target, Right}, print our Right.

Upvotes: 1

Related Questions