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

/ ListRecipes / Cookbook.ListRecipeFilterElements

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

Finding All Elements in a List Matching Certain Criteria

Problem

From a list, you want only the elements that match certain criteria.

This notion of extracting a subset of a larger list is common. It's how you find all engineers in a list of employees, all users in the "staff" group, or all the filenames you're interested in.

Solution

The fist solution is with a plain loop. We traverse the list asking for each element in it.

;; filter*: (Value -> Boolean) -> List
;; To filter al the elements in the list l that match with the predicate pred
(define (filter* predicate l)
  (let loop ((l l) (acc '()))
    (cond 
      [(null? l) acc]
      [(pred (car l)) (loop (cdr l) (append acc (list (car l))))]
      [else (loop (cdr l) acc)])))

You also can use the filter function that ships either in the SRFI 1 or in Mzlib. The signature of this filter is the very same that the one for filter*.

;; either
(require (lib "list.ss" "srfi" "1.ss" ));; for filter in the SRFI 1
;; or
(require (lib "list.ss" "mzlib")) ;; for the one in Mzlib
;; and You are ready to go

Discussion

You'd get more help if you didn't need to register (more spam too...)


Comments about this recipe

Contributors

-- IvanHernandez - 20 May 2004

(define (myfilt pred? lst)
 (cond
  ((null? lst) '())
  ((pred? (car lst)) (cons (car lst) (myfilt pred? (cdr lst))))
  (else (myfilt pred? (cdr lst)))))

(printf "(myfilt even? '(1 2 3 4 5)) -> ~a\n"
         (myfilt even? '(1 2 3 4 5)))

output: (myfilt even? '(1 2 3 4 5)) -> (2 4)

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