e r l a n g : c o o k b o o k

/ Erlang.ListExtractingSublist

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Extracting a sublist

Problem

Given a list, extract a segment specified by a start and an end index (inclusive).

Solution

Use the lists module sublist/2 or sublist/3 functions. The sublist/2 function takes the first N elements from a list, while the sublist/3 function takes a starting and ending point in the list.
% Take the first 5 elements of a list
1> L = [1,2,3,4,5,6,7,8,9,10].
[1,2,3,4,5,6,7,8,9,10]
2> lists:sublist(L,5).
[1,2,3,4,5]

% Take 5 elements from a list, starting from the third position.
3> lists:sublist(L,3,5).
[3,4,5,6,7]

Discussion

A call to either sublist will a return a newly allocated list holding the elements of the given segment. Please note that all list functions are indexed by 1.

Note: The sublist function corrresponds to using the slice operator in Python.

Contributors

Based on work by GordonWeakliem and JensAxelSoegaard.

-- BrentAFulgham - 28 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: ListRecipes
TopicOrder: 010

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest