[erlang-questions] list_element()

Henning Diedrich hd2010@REDACTED
Thu May 27 22:13:36 CEST 2010


Thank you Robert,

I'll heed your two-versions advice and provide two functions there.

Are null or undefined better than nil then, or is the desire to use such 
a non-value always a sign that an exception or error is in order?

Thanks again,
Henning

Robert Virding wrote:
> Your code is basically correct. Some points:
>
> - There is no real benefit in converting to a tuple first as you have
> to step over the elements anyway.
>
> - You should seriously consider how/what to return when  you don't
> find the element. You return nil. This means that any caller will have
> to check return value to see if it was there, which means you may have
> to propagate error checking/handling. If it *should* there then maybe
> it is best just to signal an error if it not, by just skipping that
> clause. If you were putting them in a library then you could have two
> functions, one which returns {yes,Index} | no (say) and the other
> which just returns index and fails if not found.
>
> - The atom nil has no special significance in Erlang and is seldom used.
>
> Robert
>
>
> On 27 May 2010 16:31, Henning Diedrich <hd2010@REDACTED> wrote:
>   
>> Hi list,
>>
>> I need to access a list element by index.
>>
>> I wrote a function but it looks most clumsy.
>>
>> I am looking for maximal performance. Should I instead convert the list to a
>> tuple and use element()?
>>
>> The lists are ~ 10 to 30 elements in length. (<-- not an attempt to define a
>> frame).
>>
>> For curiosity, does the below tail-recurse correctly?
>>
>>       listOrd(_, []) -> nil;
>>
>>       listOrd(Searched, List) when is_list(List) ->
>>
>>           listOrd(Searched, List, 1).
>>
>>       listOrd(_, [], _) -> nil;
>>
>>       listOrd(Searched, [ Element | Tail ], Count) ->
>>
>>           case Searched == Element of
>>               true -> Count;
>>               _ -> listOrd(Searched, Tail, Count + 1)
>>           end.
>>
>>
>>
>> Thanks for your time,
>> Henning
>>
>>     
>
>   



More information about the erlang-questions mailing list