Last active
March 6, 2017 08:15
-
-
Save LuboVarga/5df0b6bd62a22d27bf859c406661ff6d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(take). | |
-export([take/2]). | |
-include_lib("eunit/include/eunit.hrl"). | |
-spec take(integer(), [T]) -> [T]. | |
take(Count,List) when count >= 0 -> | |
takeTailRec(Count, List, []). | |
% there is nothing to take from source list, so return what we have | |
takeTailRec(_CountLeft, [], ResultAcc) -> | |
lists:reverse(ResultAcc); | |
% requested count has been taken, so return | |
takeTailRec(0, _List, ResultAcc) -> | |
lists:reverse(ResultAcc); | |
% taking one more element from source and adding it to resulting accumulator. | |
takeTailRec(CountLeft, [E|Ex], ResultAcc) -> | |
takeTailRec(CountLeft - 1, Ex, [E|ResultAcc]). | |
% some tests. on ubuntu I had to install "sudo apt-get install erlang-eunit erlang-dev" and restart current erlang shell. (perhaps installing erlang-dev was not nesseray) | |
take0empty_test() -> ?assert(take(0,[]) == []). | |
take0nonEmpty_test() -> ?assert(take(0,[$H,$e,$l,$l,$o]) == []). | |
take1empty_test() -> ?assert(take(1,[]) == []). | |
take1nonEmpty_test() -> ?assert(take(1,[$H,$e,$l,$l,$o]) == [$H]). | |
take3nonEmpty_test() -> ?assert(take(3,[$H,$e,$l,$l,$o]) == [$H,$e,$l]). | |
take13nonEmpty_test() -> ?assert(take(13,[$H,$e,$l,$l,$o]) == [$H,$e,$l,$l,$o]). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment