August 23, 2024
P18 - Extract a slice from a list.
Given two indices, I and K, the slice is the list containing the elements from and including the Ith element up to but not including the Kth element of the original list. Start counting the elements with 0.
Example:
> p18:slice(3,7, [1,2,3,4,5,6,7,8,9,10]).
[4,5,6,7]
> p18:slice(3,7, [1,2,3,4]).
[4]
erlang
-module(p18).
-export([slice/3]).
slice(St, End, Ls) ->
slice(St, End, 0, Ls).
slice(_, _, _, []) ->
[];
slice(St, End, I, [H | T]) when End == I + 1, T == []->
[H];
slice(St, End, I, [H | T]) when I >= St ->
[H | slice(St, End, I + 1, T)];
slice(St, End, I, [H | T]) ->
slice(St, End, I + 1, T).