August 21, 2024

P03 - Find the Kth element of a list.

By convention, the first element in the list is element 0.

Example:

> p03:kth([0, 1, 2, 3], 2).
  2

erlang

%
% Find the Kth element of a list.
%
-module(p03).
-export([kth/2]).

kth([Head | _], 0) ->
    Head;

kth([_ | Tail], Index) -> 
    kth(Tail, Index - 1).

%c(p03).
%p03:kth([1], 0).
%p03:kth([0, 1, 2, 3], 2).
Be first to comment
Leave a reply