[erlang-questions] array search problem

Richard A. O'Keefe ok@REDACTED
Mon Feb 2 01:49:14 CET 2015


On 31/01/2015, at 7:34 am, Roelof Wobben <r.wobben@REDACTED> wrote:

> Hello,
> 
> Im stuck again,
> 
> I have now this :
> 
> read(Key, []) ->
>  {error, Instance};
> 
> read(Key, [Key, _] )->
>  Key;
> 
This clause is clearly wrong.
You are looking for a LIST of ONE OR MORE elements,
the first of whose elements is a TUPLE of exactly
two elements, the first of which is Key.

But here you check for a list of exactly two elements,
the first of which is Key.

read(Key, [{Key,Value}|_]) ->
    ....

The result you have here is clearly wrong given the example
you previously quoted.  The result is supposed to be a
TUPLE of exactly two elements, the first of which is the
atom 'ok' and the second of which is the value you are looking
for.

> read(Key, [_, Tail] ) ->
>  read(Key, Tail).

This clause is also clearly wrong.  You are looking for
a list of at least one element where you don't care what
the first element is.  But you are checking for a list
of exactly two elements.  That is, you have
[_,Tail] where you should have [_|Tail].
  ^                              ^


Maybe it would help if you started by writing down in words
exactly what you wanted to match, and then wrote the pattern
from the outside in, drawing lines to connect the words to
the code.

Also, don't be afraid to break it down into really small steps.
It is OK to make just one decision per pattern, like this:

read(Key, [Head|Tail]) ->
    read_non_empty(Key, Head, Tail);
read(Key, []) ->
    read_empty(Key).

read_empty(_) ->
    {error,instance}.

read_non_empty(Key, {K,V}, Tail) ->
    read_non_empty(Key, K, V, Tail).

%   In order to pacify Joe Armstrong, we know have code that
%   will crash if it meets a list element that is not a pair.

read_non_empty(Key, Key, Value, _) ->
    ?what goes here since we have found what we seek?;
read_non_empty(Key, _, _, Rest) ->
    ?what goes here since we must keep looking?.

Maybe you will find it easier to do one step at a time like this.




More information about the erlang-questions mailing list