Reputation: 9589
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
Upvotes: 5
Views: 1492
Reputation: 2805
Here is a very concise alternative in pure Elixir.
> Enum.to_list(50..150//5)
[50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135,140, 145, 150]
> Enum.to_list(3..30//5)
[3, 8, 13, 18, 23, 28]
The //
part is called range step operator
: https://hexdocs.pm/elixir/1.14/Kernel.html#..///3
Upvotes: 2
Reputation: 9299
You can also use :lists.seq(From, To, Increment)
.
:lists.seq(start, length*increment, increment)
Upvotes: 3
Reputation: 11288
The answer by Gazler is a great one.
If you'd like to get a little bit more fancy you can use Stream.iterate/2
and Enum.take/2
for a similar result:
start = 1
length = 10
increment = 3
Stream.iterate(start, &(&1 + increment)) |> Enum.take(length)
#=> [1, 4, 7, 10, 13, 16, 19, 22, 25, 28]
Upvotes: 5
Reputation: 84190
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]
Upvotes: 5