Created
November 23, 2017 16:29
-
-
Save elbrujohalcon/6541a3d32ec30d320dc19145b78c114b to your computer and use it in GitHub Desktop.
lists:seq/2,3
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(my_lists). | |
-export([seq/2, seq/3]). | |
%% seq(Min, Max) -> [Min,Min+1, ..., Max] | |
%% seq(Min, Max, Incr) -> [Min,Min+Incr, ..., Max] | |
%% returns the sequence Min..Max | |
%% Min <= Max and Min and Max must be integers | |
-spec seq(From, To) -> Seq when | |
From :: integer(), | |
To :: integer(), | |
Seq :: [integer()]. | |
seq(First, Last) | |
when is_integer(First), is_integer(Last), First-1 =< Last -> | |
seq_loop(Last-First+1, Last, []). | |
seq_loop(N, X, L) when N >= 4 -> | |
seq_loop(N-4, X-4, [X-3,X-2,X-1,X|L]); | |
seq_loop(N, X, L) when N >= 2 -> | |
seq_loop(N-2, X-2, [X-1,X|L]); | |
seq_loop(1, X, L) -> | |
[X|L]; | |
seq_loop(0, _, L) -> | |
L. | |
-spec seq(From, To, Incr) -> Seq when | |
From :: integer(), | |
To :: integer(), | |
Incr :: integer(), | |
Seq :: [integer()]. | |
seq(First, Last, Inc) | |
when is_integer(First), is_integer(Last), is_integer(Inc) -> | |
if | |
Inc > 0, First - Inc =< Last; | |
Inc < 0, First - Inc >= Last -> | |
N = (Last - First + Inc) div Inc, | |
seq_loop(N, Inc*(N-1)+First, Inc, []); | |
Inc =:= 0, First =:= Last -> | |
seq_loop(1, First, Inc, []) | |
end. | |
seq_loop(N, X, D, L) when N >= 4 -> | |
Y = X-D, Z = Y-D, W = Z-D, | |
seq_loop(N-4, W-D, D, [W,Z,Y,X|L]); | |
seq_loop(N, X, D, L) when N >= 2 -> | |
Y = X-D, | |
seq_loop(N-2, Y-D, D, [Y,X|L]); | |
seq_loop(1, X, _, L) -> | |
[X|L]; | |
seq_loop(0, _, _, L) -> | |
L. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment