From f0f74f93d6cce751a4aef2576f7bce837f7b23c2 Mon Sep 17 00:00:00 2001 From: Ben Sima Date: Sat, 9 May 2020 15:02:55 -0700 Subject: Add proper replace - replace was actually replace-char - backported string-replace-substring because it's only in Guile 3 --- Alpha/String.scm | 37 +++++++++++++++++++++++++++++++++++-- Biz/Bild.scm | 4 ++-- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/Alpha/String.scm b/Alpha/String.scm index 779c2fb..c7ad61f 100644 --- a/Alpha/String.scm +++ b/Alpha/String.scm @@ -1,12 +1,15 @@ (define-module (Alpha String) - #:export (replace to-string str capitalize)) + #:export (replace replace-char to-string str capitalize)) -(define (replace s match repl) +(define (replace-char s match repl) (let ((f (lambda (a b) (let ((next-char (if (eq? a match) repl a))) (string-concatenate (list b (string next-char))))))) (string-fold f "" s))) +(define (replace s match repl) + (string-replace-substring s match repl)) + (define (to-string x) (format #f "~a" x)) @@ -22,3 +25,33 @@ (string-upcase s) (str (string-upcase (substring s 0 1)) (substring s 1 ))))) + + +;;; {String Fun: string-replace-substring} +;;; + +;; string-replace-substring By A. Wingo in +;; https://lists.gnu.org/archive/html/guile-devel/2014-03/msg00058.html +;; also in string-replace-substring guix:guix/utils.scm. + +(define (string-replace-substring str substring replacement) + "Return a new string where every instance of @var{substring} in string + @var{str} has been replaced by @var{replacement}. For example: + + @lisp + (string-replace-substring \"a ring of strings\" \"ring\" \"rut\") + @result{} \"a rut of struts\" + @end lisp + " + (let ((sublen (string-length substring))) + (with-output-to-string + (lambda () + (let lp ((start 0)) + (cond + ((string-contains str substring start) + => (lambda (end) + (display (substring/shared str start end)) + (display replacement) + (lp (+ end sublen)))) + (else + (display (substring/shared str start))))))))) diff --git a/Biz/Bild.scm b/Biz/Bild.scm index 4e1d490..1fcae96 100755 --- a/Biz/Bild.scm +++ b/Biz/Bild.scm @@ -144,14 +144,14 @@ (define ns? symbol?) (define (ns->path ns) - (let ((to-path (lambda (s) (string/replace s #\. #\/)))) + (let ((to-path (lambda (s) (string/replace-char s #\. #\/)))) (cond ((symbol? ns) (to-path (symbol->string ns))) ((string? ns) (to-path ns)) (else (error "ns should be a string or symbol"))))) (define (path->ns path) - (let ((to-ns (lambda (s) (string/replace s #\/ #\.)))) + (let ((to-ns (lambda (s) (string/replace-char s #\/ #\.)))) (cond ((symbol? path) (to-ns (symbol->string path))) ((string? path) (to-ns path)) -- cgit v1.2.3