From de2e7001e050abf544fbf628caa63daa75160c51 Mon Sep 17 00:00:00 2001 From: Steve Kemp Date: Sun, 6 Nov 2022 19:14:55 +0200 Subject: [PATCH] Added intersection, member, and union functions. These are neat to have. --- PRIMITIVES.md | 6 ++++++ stdlib/stdlib/lists.lisp | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 stdlib/stdlib/lists.lisp diff --git a/PRIMITIVES.md b/PRIMITIVES.md index d21bf75..8ffa453 100644 --- a/PRIMITIVES.md +++ b/PRIMITIVES.md @@ -286,6 +286,8 @@ Functions here include: * Is the given thing a hash? * `inc` * Increment the given variable. +* `intersection` + * Return those elements in common in the specified pair of lists. * `last` * Return the last element of the specified list. * `length` @@ -304,6 +306,8 @@ Functions here include: * Return the results of applying the specified function to every pair of elements in the given list. * `max` * Return the maximum value in the specified list. +* `member` + * Return true if the specified item is contained within the given list. * `min` * Return the maximum value in the specified list. * `nat` @@ -362,6 +366,8 @@ Functions here include: * `translate` * Translate a string of characters, via a lookup table. * Used by `lower`, and `upper`. +* `union` + * Return a list of all items in the specified two lists - without duplicates. * `upper` * Return an upper-case version of the specified string. * `upper-table` diff --git a/stdlib/stdlib/lists.lisp b/stdlib/stdlib/lists.lisp new file mode 100644 index 0000000..f25bc54 --- /dev/null +++ b/stdlib/stdlib/lists.lisp @@ -0,0 +1,39 @@ +;;; lists.lisp - Some list-utility functions + +;; These were adapted from Rob Pike's lisp +;; +;; https://github.com/robpike/lisp +;; +;; which in turn were derived from code in "LISP 1.5 Programmer's Manual" +;; by McCarthy, Abrahams, Edwards, Hart, and Levin, from MIT in 1962. +;; + + +(set! member (fn* (item list) + "Return true if the specified item is found within the given list. + +See-also: intersection, union." + + (cond + (nil? list) false + (eq item (car list)) true + true (member item (cdr list))))) + +(set! union (fn* (x y) + "Return the union of the two specified lists. + +See-also: intersection, member" + (cond + (nil? x) y + (member (car x) y) (union (cdr x) y) + true (cons (car x) (union (cdr x) y)) + ))) + +(set! intersection (fn* (x y) + "Return the values common to both specified lists + +See-also: member, union." + (cond + (nil? x) nil + (member (car x) y) (cons (car x) (intersection (cdr x) y)) + true (intersection (cdr x) y))))