[erlang-questions] array search problem

Fred Hebert mononcqc@REDACTED
Fri Jan 30 18:11:08 CET 2015


Hi Roelof.

I recognize these exercises from the Francesco Cesarini and Simon
Thompson book (published by O'Reilly).

If you cannot work through these exercises, I strongly recommend you go
back to the chapter that precedes them and re-read it again until it
clicks, or possibly go back to a chapter you may have skipped.

It will be a better use of your time to go through it and understand it
properly rather than come to the mailing list and ask people in here to
do that part on your behalf.

That being said, the trick for this exercise is to go through recursion.

The database you mention uses *lists* (*arrays* are a different data
type and have a module to that name, too). Lists are a data structure
defined recursively:

    [3, 2, 1]
    [3 | [2, 1]]
    [3 | [2 | [1]]]
    [3 | [2 | [1|[]]]]

Those 4 lists are equivalent. So when you traverse a list by going
[Head | Tail], on each of these, you take one element and then are left
with the rest.

The definition is therefore [FirstElement | RestOfListWhichIsAlsoAList].
The last element of a list is necessarily [], the empty list.

Recursive functions have two main kinds of clauses (I'm going with an
informal definition here): base cases, and the regular case. The base
case is whenever recursion cannot proceed further. The base case is when
you can proceed further.

To search elements in a list, your base case will therefore be '[]', the
empty list, where you can't search further.
The base case will be the other [Element | Rest].

So your function to search in a DB? To avoid giving you the answer, you
know that if you can't look further, you haven't found the element.
Therefore,

    lookup(Element, []) ->
        {error, not_found};
    lookup(Element, [??? | RestOfList]) ->
        ???.

Can you fill in the blanks? If not, go back a few chapters. There's no
shame in doing that and making sure you understand things right before
moving on to more difficult topics.

Regards,
Fred.

On 01/30, Roelof Wobben wrote:
> Hello,
> 
> Im still struggeling to make the database exercise working.
> 
> I have to implement a read method which outputs as this :
> 
> 5> db:read(francesco, Db2).
> {ok,london}
> 6>  Db3 = db:write(joern, stockholm, Db2).
> [{joern,stockholm},{lelle,stockholm},{francesco,london}]
> 7>  db:read(ola, Db3).
> {error,instance}
> 
> To achieve this do I need to use a try catch or can  I achieve this with
> only pattern matching.
> 
> Roelof
> 
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list