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

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

I know that it should be easy, but I can’t crack it. I tried lists, stream functions, etc.

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

Range allows me to choose start and end, but not 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
+4
source share
3 answers

You can do this with the understanding:

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

The following values ​​are shown in the example above:

start = 1
length = 10
increment = 3

You need extra brackets for the negative range:

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

Gazler's answer is a great option.

, Stream.iterate/2 Enum.take/2 :

start = 1
length = 10
increment = 3
Stream.iterate(start, &(&1 + increment)) |> Enum.take(length)
#=> [1, 4, 7, 10, 13, 16, 19, 22, 25, 28]
+5

You can also use :lists.seq(From, To, Increment).

:lists.seq(start, length*increment, increment)
+2
source

Source: https://habr.com/ru/post/1625156/


All Articles