Skip to content

Instantly share code, notes, and snippets.

@gorkaio
Last active May 12, 2020 13:11
Show Gist options
  • Save gorkaio/404241b7b24f7275aa9b132e8b01c8dd to your computer and use it in GitHub Desktop.
Save gorkaio/404241b7b24f7275aa9b132e8b01c8dd to your computer and use it in GitHub Desktop.
-module(take).
-export([take/2]).
-export([take_test/0]).
-spec take(integer(), [T]) -> [T].
take(_, []) -> [];
take(0, _) -> [];
take(N, L) -> take(N, L, []).
take(_, [], Ac) -> lists:reverse(Ac);
take(0, _, Ac) -> lists:reverse(Ac);
take(N, [H|T], Ac) -> take(N-1, T, [H|Ac]).
take_test() ->
[] = take(0, "hello"),
"hell" = take(4, "hello"),
"hello" = take(5, "hello"),
"hello" = take(9, "hello"),
passed.
@elbrujohalcon
Copy link

Nice tests!

@gorkaio
Copy link
Author

gorkaio commented May 8, 2020

Thinking about your comment on tests for the previous gists I played a little with this one and, interestingly, take(-2, "hello") still works as expected... though I'm not sure why 😅

@elbrujohalcon
Copy link

One thing I missed before was a subtle error on your specs…
integer is the type of the atom integer.
integer() is the type of all integer numbers.

@gorkaio
Copy link
Author

gorkaio commented May 12, 2020

Fixed 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment