s c h e m a t i c s : c o o k b o o k

/ ListRecipes / Cookbook.ListRecipeSplittingInHalves

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Splitting a list in halves

Problem

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

Solution

; split-in-halves : list -> (values list list)
;  return two lists of lengths differing with at most one
(define (split-in-halves l)
  (let loop ([front '()]
             [slow  l]
             [fast  l])
    (cond
      [(null? fast)         (values front
                                    slow)]
      [(null? (cdr fast))   (values (cons (car slow) front)
                                    (cdr slow))]
      [else                 (loop (cons (car slow) front)
                                  (cdr slow)
                                  (cddr fast))])))

; split-in-halves! : list -> (values list list)
;  return two lists of lengths differing with at most one;
;  modifies the argument
(define (split-in-halves! l)
  (let loop ([slow (cons 'foo l)]
             [fast (cons 'bar l)])
    (cond
      [(or (null? fast)
           (null? (cdr fast))) (let ([back (cdr slow)])
                                 (set-cdr! slow '())
                                 (values l back))]
      [else                    (loop (cdr slow)
                                     (cddr fast))])))

> (split-in-halves (list 1 2 3 4 5))
(3 2 1)
(4 5)
> (split-in-halves (list 1 2 3 4 5 6))
(3 2 1)
(4 5 6)

> (split-in-halves! (list 1 2 3 4 5))
(1 2 3)
(4 5)
> (split-in-halves! (list 1 2 3 4 5 6))
(1 2 3)
(4 5 6)

Discussion

The solutions does not use length and thus make only one traversal of the list.

-- JensAxelSoegaard - 18 Apr 2004

CookbookForm
TopicType: Recipe
ParentTopic: ListRecipes
TopicOrder:

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, 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