soddik
soddik

Reputation: 89

How to retrieve a specific value within a map function?

I have this function :

Headers = "hellohellohello".
lists:map(fun(X) -> isExists(X,Headers) end, ["h","he","hell","hello",...]).

The result is a list of Boolean, lets say :

[false,false,false,true,...] 

Note that the result contain one "true" I would like to get the value of the :

true

which is

"hello"

in our case.

Upvotes: 0

Views: 386

Answers (1)

Steve Vinoski
Steve Vinoski

Reputation: 20014

You can use lists:filter/2 to get a list of results for which isExists/2 returns true:

1> Headers = "hellohellohello".
"hellohellohello"
2> lists:filter(fun(X) -> isExists(X,Headers) end, ["h","he","hell","hello"]).
["hello"]

But that returns a list, not a value. Alternatively, you could use lists:map/2 to pair each value in the list with the result of passing it to isExists/2, and then use lists:keyfind/3 to extract the result:

4> lists:keyfind(true, 1, lists:map(fun(X) -> {isExists(X,Headers), X} end, ["h","he","hell","hello"])).
{true,"hello"}

But this alternative requires multiple list traversals, and it returns a tuple from which you'd have to extract the value.

Perhaps the best alternative is to use lists:foldl/3:

3> lists:foldl(fun(X,Acc) -> case isExists(X,Headers) of true -> X; false -> Acc end end, false, ["h","he","hell","hello"]).
"hello"

If there are no matching results, the initial value of the accumulator, which in this example is false, will be returned instead.

Upvotes: 4

Related Questions