Skip to content

Instantly share code, notes, and snippets.

@granolocks
Created June 10, 2014 13:29
Show Gist options
  • Select an option

  • Save granolocks/94d77145024f270e173b to your computer and use it in GitHub Desktop.

Select an option

Save granolocks/94d77145024f270e173b to your computer and use it in GitHub Desktop.
test_helper.erl
-module(list_helper).
-author("granolocks").
-export([
test/0,
test/1,
test/2,
index/2
]).
%% Based on ruby index behavior as follows:
%%
%% 2.1.2 :016 > a = [1,2,3,4,5]
%% => [1, 2, 3, 4, 5]
%% 2.1.2 :017 > keys = [-6,-5,-1,0,4,5]
%% => [-6, -5, -1, 0, 4, 5]
%% 2.1.2 :018 > keys.map{|k| a[k]}
%% => [nil, 1, 5, 1, 5, nil]
%%
%% %% Note: I am replacing nil with false.
%%
test() ->
List = [1,2,3,4,5],
Tests = [
{index(-6, List), false},
{index(-5, List), 1},
{index(-1, List), 5},
{index(0, List), 1},
{index(4, List), 5},
{index(5, List), false},
{i(-6, List), false},
{i(-5, List), 1},
{i(-1, List), 5},
{i(0, List), 1},
{i(4, List), 5},
{i(5, List), false},
{x(-6, List), false},
{x(-5, List), false},
{x(-1, List), false},
{x(0, List), 1},
{x(4, List), 5},
{x(5, List), false}
], test(Tests).
test(Tests) ->
[ test(A, B) || {A, B} <- Tests] =:= [ true || _ <- Tests ].
test(X,X) -> io:format("test passed for ~p~n", [X]), true;
test(_,X) -> io:format("test failed for ~p~n", [X]), false.
index(Index,List) when Index < 0 ->
index((abs(Index)-1), lists:reverse(List));
index(_,[]) -> false;
index(0,[Head|_]) -> Head;
index(Index,[_|Tail]) -> index(Index-1,Tail).
%% minified
i(I,L)when I<0->i(abs(I)-1,lists:reverse(L));i(_,[])->false;i(0,[H|_])->H;i(I,[_|T])->i(I-1,T).
%% minified, no negative lookups
x(I,_)when I<0->false;x(_,[])->false;x(0,[H|_])->H;x(I,[_|T])->x(I-1,T).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment