From 93d0ba9844dbba55658ce9c0d8570e294bd096b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20H=C3=B6rnquist?= Date: Mon, 10 Apr 2023 22:02:44 +0200 Subject: Add init+last. --- doc/ref/guile/util.texi | 5 +++++ module/hnh/util.scm | 14 ++++++++++++-- tests/test/hnh-util.scm | 3 +++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/doc/ref/guile/util.texi b/doc/ref/guile/util.texi index 32e7543f..f60e2059 100644 --- a/doc/ref/guile/util.texi +++ b/doc/ref/guile/util.texi @@ -113,6 +113,11 @@ See @var{find-extreme} @end lisp @end defun +@defun init+last list +Returns two values: everything except the last element of @var{list}, +and the last element of @var{list}. +@end defun + @defun take-to lst n Equivalent to @var{take}, but return everything (instead of crash) if n > (length lst). diff --git a/module/hnh/util.scm b/module/hnh/util.scm index 759cdd48..c88a029e 100644 --- a/module/hnh/util.scm +++ b/module/hnh/util.scm @@ -17,6 +17,7 @@ find-extreme find-min find-max filter-sorted != + init+last take-to string-take-to string-first @@ -150,9 +151,12 @@ +;; TODO this is called flip in Haskell land (define (swap f) (lambda args (apply f (reverse args)))) - +;; Swap would be +;; (define (swap p) +;; (xcons (car p) (cdr p))) ;; Allow set to work on multiple values at once, ;; similar to Common Lisp's @var{setf} @@ -253,6 +257,12 @@ ;; (define (!= a b) (not (= a b))) (define != (negate =)) + +(define (init+last l) + (let ((last rest (car+cdr (reverse l)))) + (values (reverse rest) last))) + + (define (take-to lst i) "Like @var{take}, but might lists shorter than length." (if (> i (length lst)) @@ -396,7 +406,7 @@ (reverse (cons (map list last) rest )))))) ;; Given an arbitary tree, do a pre-order traversal, appending all strings. -;; non-strings allso allowed, converted to strings and also appended. +;; non-strings also allowed, converted to strings and also appended. (define (string-flatten tree) (cond [(string? tree) tree] [(list? tree) (string-concatenate (map string-flatten tree))] diff --git a/tests/test/hnh-util.scm b/tests/test/hnh-util.scm index dc64a3aa..4e50ac1b 100644 --- a/tests/test/hnh-util.scm +++ b/tests/test/hnh-util.scm @@ -202,6 +202,9 @@ (test-assert "not equal" (!= 1 2))) +(test-group "init+last" + 'TODO) + (test-group "take-to" (test-equal "Take to" '() (take-to '() 5))) -- cgit v1.2.3