summaryrefslogtreecommitdiff
path: root/module/srfi
diff options
context:
space:
mode:
authorLudovic Courtès <ludo@gnu.org>2020-06-17 16:59:50 +0200
committerLudovic Courtès <ludo@gnu.org>2020-06-17 17:25:23 +0200
commit0360843acee98f26598d8f77eda880a03ea3be93 (patch)
tree49420c3904cd029a9e85629d421acd818134d119 /module/srfi
parent2e2e13c40a38a399daf6466f95c8975600ab5ded (diff)
downloadguile-0360843acee98f26598d8f77eda880a03ea3be93.tar.gz
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.
Diffstat (limited to 'module/srfi')
-rw-r--r--module/srfi/srfi-1.scm13
1 files changed, 12 insertions, 1 deletions
diff --git a/module/srfi/srfi-1.scm b/module/srfi/srfi-1.scm
index c0ee53548..e5b28e777 100644
--- a/module/srfi/srfi-1.scm
+++ b/module/srfi/srfi-1.scm
@@ -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."