TWiki . Cookbook . ListRecipeFilterElements

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:

----- Revision r1.3 - 26 Mar 2006 - 00:48 GMT - JensAxelSoegaard
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.