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

/ Erlang.ListSplittingInHalves

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

Splitting a list in halves

Problem

Splitting a list in two lists whose lengths are half of the original.

Solution

Use the lists:split function.

1> List = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16].
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
2> lists:split(length(List) div 2, List).
{[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]}
3> List2 = [1,2,3,4,5,6,7].
[1,2,3,4,5,6,7]
4> lists:split(length(List2) div 2, List2).
{[1,2,3],[4,5,6,7]}
Note the use of integer division by the div function to provide proper input to the function. Also note that the split function will work properly on lists that can't be split into two equal lengths.

Discussion

The obvious lists:split solution works, but is not optimal, because it traverses the list two times (once to get the length of the list, and another time to find the element at which to break the list).

We can provide a better solution by

% split_in_halves : list -> {list,list}
%  return two lists of lengths differing with at most one
sih_loop(Front, Slow, []) -> {lists:reverse(Front), Slow};
sih_loop(Front, Slow, Fast) ->
    Y = tl(Fast),
    if
        Y == [] -> { lists:reverse([hd(Slow) | Front]), tl(Slow) };
        true    -> sih_loop( [hd(Slow) | Front],
                             tl(Slow), tl(tl(Fast)))
    end.

split_in_halves(List) ->
    sih_loop([], List, List).

5> split_in_halves([1,2,3,4,5]).
{[1,2,3],[4,5]}
6> split_in_halves([1,2,3,4,5,6]).
{[1,2,3],[4,5,6]}

Contributors

Based on work by JensAxelSoegaard.

-- BrentAFulgham - 29 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: ListRecipes
TopicOrder: 050

 
 
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