Lisp - Getting Subset from a Set



We've multiple ways to get a subset from a Set. In this chapter, we'll discuss various ways to perform operations on a Set to get subset.

Using predicates to get subset

We can use predicates to filter elements using remove-if-not predicate

Example - Get odd numbers

; get odd numbers
(defun get-odd-numbers (set)
   (remove-if-not #'oddp set)
)

; define a set of values
(defvar my-set '(1 2 3 4 5 6))

; add a new value
(setf my-set (get-odd-numbers my-set))
    
; print the set of odd numbers
(print my-set)

Output

When you execute the code, it returns the following result −

(1 3 5)

Example - Using lambda function

; get numbers less than 5
(defun get-numbers (set)
   (remove-if-not #'(lambda (x) (< x 5)) set)
)

; define a set of values
(defvar my-set '(1 2 3 4 5 6))

; add a new value
(setf my-set (get-numbers my-set))
    
; print the set of numbers less than 5
(print my-set)

Output

When you execute the code, it returns the following result −

(1 2 3 4)

Using Intersection to get subset

We can use intersection function to get the subset as set of common elements from a set as shown below:

Example - Using lambda function

; get common numbers
(defun get-numbers (set desired-set)
   (intersection set desired-set)
)

; define a set of values
(defvar my-set '(1 2 3 4 5 6))

; add a new value
(setf my-set (get-numbers my-set '(1 2)))
    
; print the set of numbers
(print my-set)

Output

When you execute the code, it returns the following result −

(1 2)

Using set-difference to get subset

We can use set-difference function to get the subset by removing extra elements as shown below:

Example - Using lambda function

; get numbers not in set
(defun get-numbers (set unwanted-set)
   (set-difference set unwanted-set)
)

; define a set of values
(defvar my-set '(1 2 3 4 5 6))

; add a new value
(setf my-set (get-numbers my-set '(1 2)))
    
; print the set of numbers
(print my-set)

Output

When you execute the code, it returns the following result −

(3 4 5 6) 

Using subseq to get subset

We can use subseq function to get the subset as shown below:

Example - Using lambda function

; get numbers in set
(defun get-numbers (set start end)
   (subseq set start end)
)

; define a set of values
(defvar my-set '(1 2 3 4 5 6))

; add a new value
(setf my-set (get-numbers my-set 1 4))
    
; print the set of numbers
(print my-set)

Output

When you execute the code, it returns the following result −

(2 3 4) 
Advertisements