Erlang Thursday – lists:seq

My goal of these Erlang Thursday’s for the next while will be to show off the “corresponding” functions in Erlang for the Ruby methods I highlight on Tuesday. I am hoping that by having these Erlang Thursday line up with the Ruby Tuesday for the week, that I can make Erlang be less foreign and intimidating by establishing a common thread of discussion. I would love to know your thoughts on how well this secondary goal is working for you the reader.

That being said, since I talked about Ruby’s Range this week, today’s Erlang function is lists:seq/2 and lists:seq/3.

If you remember from the sidebar of last weeks Erlang Thursday, the number at the end of the function name means the arity (number of arguments) of the function.

The function lists:seq/2 takes a beginning and an ending integer and produces a list of integers including both the beginning and ending value.

lists:seq(1, 10).     
% [1,2,3,4,5,6,7,8,9,10]
lists:seq(1, 1). 
% [1]

The 3-arity version of lists:seq introduces the increment as the third argument:

lists:seq(1, 10, 3).  
% [1,4,7,10]

The increment value can be negative as well, allowing for counting down from one number to another.

lists:seq(20, 10, -1).
% [20,19,18,17,16,15,14,13,12,11,10]
lists:seq(20, 10, -5).
% [20,15,10]

The list:seq functions will throw an exception if given invalid starting and ending values, unlike the Ruby Range which returns an empty set.

lists:seq(10, 1).   
% ** exception error: no function clause matching lists:seq(10,1) (lists.erl, line 241)
lists:seq(1, 10, 0).
% ** exception error: no true branch found when evaluating an if expression
%      in function  lists:seq/3 (lists.erl, line 262)
lists:seq(1, 10, -2).
% ** exception error: no true branch found when evaluating an if expression
%      in function  lists:seq/3 (lists.erl, line 262)
lists:seq(10, 1, 2).
% ** exception error: no true branch found when evaluating an if expression
%      in function  lists:seq/3 (lists.erl, line 262)

–Proctor