From 3c9b5f433da80581b43b11d407540633c0636fec Mon Sep 17 00:00:00 2001 From: Jan Nieuwenhuizen Date: Sun, 29 Apr 2018 18:21:52 +0200 Subject: [PATCH] mes: Add string-contains. * module/srfi/srfi-13.mes (string-contains): New function. * tests/srfi-13.test ("string-contains"): Test it. ("string-contains not"): --- module/srfi/srfi-13.mes | 12 ++++++++++++ tests/srfi-13.test | 6 ++++++ 2 files changed, 18 insertions(+) diff --git a/module/srfi/srfi-13.mes b/module/srfi/srfi-13.mes index 859e5160..01765d40 100644 --- a/module/srfi/srfi-13.mes +++ b/module/srfi/srfi-13.mes @@ -120,3 +120,15 @@ (let loop ((lst (reverse (string->list s))) (prev nil')) (if (null? lst) prev (loop (cdr lst) (cons' (car lst) prev)))))) + +(define (string-contains string needle) + (let ((needle (string->list needle))) + (let loop ((string (string->list string)) (i 0)) + (and (pair? string) + (let match ((start string) (needle needle) (n i)) + (if (null? needle) i + (and (pair? start) + (if (eq? (car start) (car needle)) + (or (match (cdr start) (cdr needle) (1+ n)) + (loop (cdr string) (1+ i))) + (loop (cdr string) (1+ i)))))))))) diff --git a/tests/srfi-13.test b/tests/srfi-13.test index 1e6a9851..d7f5f892 100755 --- a/tests/srfi-13.test +++ b/tests/srfi-13.test @@ -62,4 +62,10 @@ exit $? (pass-if-equal "string-drop-right" "foo" (string-drop-right "foobar" 3)) +(pass-if-equal "string-contains" 3 + (string-contains "foobar" "bar")) + +(pass-if-not "string-contains not" + (string-contains "fuba" "bar")) + (result 'report)