Skip to content

erlangsters/slice

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Slice API for lists

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

It implements a slice API allowing you to emulate the Python index notation in Erlang and Elixir. It's made of the following two functions.

  • slice:index/2
  • slice:range/2

Consider a list like ['a', 'b', 'c', 'd', 'e'] in Python. With its index notation you can easily retrieve the last element, the last three elements, or let's say, 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 the slice API, you can easily compute those elements and sub-lists using the same values.

Getting started

Let's consider the very same list in Erlang.

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

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

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

The slice:index/2 function uses a 0-based index and returns the value that must be passed to the lists:nth/2 function to compute the element.

To compute a sub-list, use the slice:range/2 function. For instance, here is how to compute the last 3 elements, and the whole list without the first and last element.

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

The slice:range/2 function uses 0-based indexes and returns the values that must be passed to the lists:sublist/3 function to compute the sub-list.

It's essentially just that. For the details of the API, refer to the documentation for more information.

About

Slice API to emulate Python index notation in Erlang and Elixir.

Topics

Resources

License

Stars

Watchers

Forks

Languages