简体   繁体   中英

How to get an element from a list of pairs in Erlang

I'm trying to make a function that recursively returns an element from a list of pairs. It takes two arguments, a list of pairs (an association list), and a Value, if the value matches the first element of a pair in a list, then it should return the second element of the pair. Else return an error if the value does not match. For example, searchpair([{K,V}], K). Should return V.

Here's what I've tried. Not sure how to add in the tuple and recurse on it.

   searchpair([], _) -> error;
   searchpair([[K, V] | Rest], Search) when V = Search -> K;
   searchpair([_ | Rest], Search) -> seachPair(Rest, Search).

You don't need a when , you can bind the K directly:

searchpair([], _) ->
    error;
searchpair([{K,V} | _Rest], K) ->
    V;
searchpair([_T | Rest], Search) ->
    searchpair(Rest, Search).

Also, a tuple is not a list. Moreover, function names are case sensitive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM