Skip to content

Latest commit

 

History

History
70 lines (48 loc) · 2.79 KB

File metadata and controls

70 lines (48 loc) · 2.79 KB

Python-style slice calculations for Erlang lists

Erlangsters Repository Supported Erlang/OTP Versions Current Version License Build Status Documentation Link

Python-style slice calculations for Erlang lists through slice:index/2 and slice:range/2.

Consider a list like ['a', 'b', 'c', 'd', 'e'] in Python. With its slice notation you can easily retrieve the last element, the last three elements, or the whole list without the first and last element.

l = ['a', 'b', 'c', 'd', 'e']
print(l[-1])   # 'e'
print(l[-3:])  # ['c', 'd', 'e']
print(l[1:-1]) # ['b', 'c', 'd']

With slice, you can emulate the same behavior. It takes Python-like slice inputs, including negative indexes and omitted bounds, and turns them into values that fit the standard Erlang list APIs.

Written by the Erlangsters community and released under the MIT license.

Getting started

Let's consider the same list in Erlang.

List = [a, b, c, d, e].

To compute a single element, use slice:index/2. For instance, here is how to compute the last element.

Index = slice:index(length(List), -1).
e = lists:nth(Index, List).

slice:index/2 takes a 0-based slice index and returns a 1-based index suitable for lists:nth/2.

To compute a sub-list, use slice:range/2. Here is how to compute the last three elements.

{Start, Length} = slice:range(length(List), {-3, undefined}).
[c, d, e] = lists:sublist(List, Start, Length).

And here is how to compute the whole list without the first and last element.

{Start, Length} = slice:range(length(List), {1, -1}).
[b, c, d] = lists:sublist(List, Start, Length).

slice:range/2 takes 0-based slice indexes and returns a 1-based start position and a length suitable for lists:sublist/3.

Omitted bounds work the same way as in Python slices. For instance, {undefined, 3} means the first three elements, and {undefined, undefined} means the whole list.

For the details of the API, refer to the documentation for more information.

Installing the library

To use slice in a rebar3 project, add it to your rebar.config.

{deps, [
  {slice, {git, "https://github.com/erlangsters/slice.git", {tag, "0.0.1"}}}
]}.