Exterval - Inclusive/Exclusive Real Valued Intervals

I was finding myself needing a library to check for real-valued interval memberships. This was from writing libraries whose parameters must adhere to these restrictions, such as regularization terms or learning rates.

The API is simple for interval creation and supports the Enumerable protocol when a interval step is defined.

Here’s a sample of the API:

iex> import Exterval
iex> ~I<[1, 10)//2>
[1, 10)//2
iex> ~I<[1, 10)//2> |> Enum.to_list()
[1.0, 3.0, 5.0, 7.0, 9.0]
iex> ~I<[1, 10)//2> |> Enum.reduce(&+/2)
25.0
iex> ~I<[-1, 3)//-0.5> |> Enum.to_list()
[2.5, 2.0, 1.5, 1.0, 0.5, 0.0, -0.5, -1.0
iex> ~I<[1, 10]> |> Enum.count()
:infinity
iex> ~I<[1, 10)//2> |> Enum.count()
4
iex> ~I<[-2,-2]//1.0> |> Enum.count()
1
iex> ~I<[1,2]//0.5> |> Enum.count()
3
iex> ~I<[-2,-1]//0.75> |> Enum.count()
2

iex> 1 in ~I<[1, 10]>
true
iex> 1 in ~I<[1, 10)//2>
true
iex> 3 in ~I<(1, 10)//2>
true

Feedback is much appreciated :+1:

1 Like

Finally found time to do a quick write-up about this library and sigils in general: Elevate Your Elixir With Sigils

Also pushed some updates in the form of a v0.2.0 release to allow for string interpolation within the interval creation.

This required changing from ~I to ~i since only lowercase sigils allow for string interpolation. But now you can declare intervals as so:

iex> min = 0
iex> ~i<[#{min + 1}, 10)//2>
[1.0,10.0)//2.0

Currently using this tiny 1-file library to support parameter validation in two of my other libraries and love the simplicity of it so far.