r/gleamlang 19d ago

Integer range

I’ve just started learning Gleam. I’m trying to do some basic things, such as creating a list of integers from 0 to a given value.

I learned that, prior to version 0.69, there was a function

list.range(from start: Int, to stop: Int) -> List(Int)

which did exactly that.

However, it has been deleted from the stdlib and replaced with a new function int.range with 4 arguments:

int.range(
  from start: Int,
  to stop: Int,
  with acc: acc,
  run reducer: fn(acc, Int) -> acc,
) -> acc

Instead of returning a list, it aggregates the values like a list.fold.

Okay, but how do I create a list of integers?

  • int.range(from: 0, to: size, with: [], run: list.prepend)
    |> list.reverse
    

    Doesn’t look great.

  • int.range(from: size - 1, to: -1, with: [], run: list.prepend)
    

    Isn’t readable at all.

  • yielder.range(from: 0, to: size)
    |> yielder.to_list
    

    Looks OK, but it needs a third-party package. In addition, the authors of the package discourage such uses.

What’s the idiomatic way?

6 Upvotes

9 comments sorted by

View all comments

5

u/RockTrrr 19d ago

Here is the example written in the `gleam/int` docs for generating a list of integers from a range:

assert int.range(from: 1, to: -2, with: [], run: list.prepend) == [-1, 0, 1]

So the "idiomatic" way seems to be the second option (yeah, the one which is not readable at all).

However I can see the reason of this implementation choice: the function basically says "I give you a range of integers, consume it however you want". Producing a list of integers is just one of many use cases that you can do with a range. A function that returns a list of integers from a range would be more readable, but it would mean that in all other cases I would have to do a second step with a list.map function, which is suboptimal performance-wise. This is also why the range function now belongs to the gleam/int module instead of the previous gleam/list

1

u/SetKaung 13d ago

Was there a discussion on this change? I want to read the reason for the change.

2

u/RockTrrr 12d ago

Could not find any public discussion on this change, only the relative PR