Extracting a Sublist
From Erlang Community
(Difference between revisions)
| Revision as of 13:46, 24 September 2006 (edit) Ayrnieu (Talk | contribs) (it corresponds to lots of things in lots of languages. Is python special? Also, 'newly allocated' doesn't matter in this non-destructive language.) ← Previous diff |
Current revision (23:47, 11 September 2007) (edit) (undo) Serpent (Talk | contribs) (Correct the description of sublist/3) |
||
| (One intermediate revision not shown.) | |||
| Line 1: | Line 1: | ||
| == Problem == | == Problem == | ||
| - | Given a list, extract a segment specified by a start and an | + | Given a list, extract a segment specified by a start index and an optional length. |
| == Solution == | == 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 | + | 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 point in the list and the maximum number of elements to extract. |
| <code> | <code> | ||
| Line 17: | Line 17: | ||
| </code> | </code> | ||
| - | Please note that all | + | Please note that all functions assume the position numbering starts at 1. |
| - | + | ||
| [[Category:CookBook]][[Category:ListRecipes]] | [[Category:CookBook]][[Category:ListRecipes]] | ||
Current revision
[edit] Problem
Given a list, extract a segment specified by a start index and an optional length.
[edit] 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 point in the list and the maximum number of elements to extract.
% 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] |
Please note that all functions assume the position numbering starts at 1.

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati

