1
Fork 0
mirror of https://git.savannah.gnu.org/git/guile.git synced 2025-06-15 08:10:17 +02:00

srfi-1: Rewrite 'find' in Scheme.

This halves the wall-clock time of:

  guile -c '(use-modules (srfi srfi-1)) (define lst (make-list 100000000 1)) (find zero? lst)'

and yields an 18% speedup on:

  guile -c '(use-modules (srfi srfi-1)) (define lst (make-list 100000000 1)) (find (lambda (x) (= 2 x)) lst)'

* libguile/srfi-1.c (scm_srfi1_find): Remove.
* libguile/srfi-1.h (scm_srfi1_find): Likewise.
* module/srfi/srfi-1.scm (find): New procedure.
* doc/ref/srfi-modules.texi (SRFI-1 Searching): Adjust docstring.
This commit is contained in:
Ludovic Courtès 2020-06-17 16:59:50 +02:00
parent 2e2e13c40a
commit 0360843ace
4 changed files with 16 additions and 29 deletions

View file

@ -1,6 +1,6 @@
;;; srfi-1.scm --- List Library
;; Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009, 2010, 2011, 2014 Free Software Foundation, Inc.
;; Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009, 2010, 2011, 2014, 2020 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
@ -720,6 +720,17 @@ the list returned."
;;; Searching
(define (find pred lst)
"Return the first element of @var{lst} that satisfies the predicate
@var{pred}, or return @code{#f} if no such element is found."
(check-arg procedure? pred find)
(let loop ((lst lst))
(and (not (null? lst))
(let ((head (car lst)))
(if (pred head)
head
(loop (cdr lst)))))))
(define (take-while pred ls)
"Return a new list which is the longest initial prefix of LS whose
elements all satisfy the predicate PRED."