Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make list of integers with a start, length and increment in Elixir?

Tags:

elixir

I would like to generate a list of integers. I have the starting value, the increment value and the length of the list.

I know this should be simple, but I can't crack it. I have tried list comprehensions, Stream functions, etc.

Here is what I've tried and what didn't work:

A range allows me to choose the start and end, but not the increment

1..3 |> Enum.to_list()

This list comprehension works, but is it the "best" way?

start = 1
length = 3
increment = 2
for i <- 0..length-1, do: start + i*increment
like image 854
Josh Petitt Avatar asked Dec 11 '22 18:12

Josh Petitt


1 Answers

You can do this with a comprehension:

for x <- 1..10, do: x * 3
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

In the above example, the following are the values you specified:

start = 1
length = 10
increment = 3

You will need additional parentheses for a negative range:

for x <- -1..(-10), do: x * 3 
[-3, -6, -9, -12, -15, -18, -21, -24, -27, -30]
like image 75
Gazler Avatar answered May 10 '23 22:05

Gazler