Search code examples
erlang

Erlang get the nth element


I'd like to get the nth element.

-module(lab02).
-export([functionGetnth/2]).

functionGetnth([], _N) ->
    {error, no_such_element};
functionGetnth([H|_T], 1) -> H;
functionGetnth([H|T], N) when N > 1 ->
    functionGetnth([H|T], N-1).

How can I delete the Head while the Head isn't the nth position?


Solution

  • There is already such function in the standard library, see lists:nth/2.

    If you insist on making your own, you need to recurse only on the tail (T) in your third clause, thus discarding the head (H), i.e.:

    functionGetNth(T, N-1).