Erlang Mailing Lists

Author Message

<  Erlang  ~  searching for an item in a list

ishmael
Posted: Tue Aug 05, 2008 9:07 am Reply with quote
Joined: 23 Jul 2008 Posts: 9 Location: RSA
Hi,

I have a list of tuples I want to search.
I want the module to search the list for a name and return the related phone number or not_found, can anybody help?
Code:
-module(search).
-export([find_phone/2]).

 
 find_phone([{Name, Phone}|_], Name) ->
      {found,Phone};
 find_phone([_|T], Name) ->
      {T, Phone}.
 find_phone([], Name) ->
    not_found.
View user's profile Send private message
Mazen
Posted: Tue Aug 05, 2008 11:01 am Reply with quote
User Joined: 20 Jul 2006 Posts: 164 Location: London
Hi Ishmael,

I suggest you take a look at lists:keysearch/3, it will do the work for you and you don't have to create a function for it (unless you want to wrap the response to return something else as I suspect you want in your case)

Here is the link:
http://www.erlang.org/doc/man/lists.html

Code:

find_phone(List, Name) ->
    %% E.g.
    %% List = [{"Mazen","555-123456"} | ...],
    %% Name = "Mazen",
    case lists:keysearch(Name, 1, List) of
        {value, {Name,Phonenumber}} ->
            {found, Phonenumber};
        false ->
            not_found
    end.


/Mazen
View user's profile Send private message
dsmith
Posted: Mon Aug 11, 2008 2:20 am Reply with quote
User Joined: 08 Aug 2007 Posts: 41 Location: Toronto
Ishmael,

Use Mazen suggestion in practise, but this is the code you were trying for ...

Code:

-module(search).
-export([find_phone/2]).
 
 find_phone([], _) ->
    not_found;
 find_phone([{Name, Phone}|_], Name) ->
      {found,Phone};
 find_phone([_|T], Name) ->
      find_phone(T, Name).

View user's profile Send private message

Display posts from previous:  

All times are GMT
Page 1 of 1
This forum is locked: you cannot post, reply to, or edit topics.

Jump to:  

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum