Lisp - Searching in List



Lisp provides various functions to find an element in a List. Each function has its own merits and demerits. In this chapter we'll explore them one by one with the help of examples.

find function

find function searches for an element, returns the first match. Returns false if element is not found.

Syntax

(find element list :test :key)

Arguments

  • element− Element to search.

  • list− A list to be searched.

  • :test− A function to be used for comparison

  • :key− A function to be applied on each element before comparison

Returns

This function returns the first match, nil if not found.

Example - Using find to get matched element

; prints C
(print(find 'c '(a b C d e) :test #'equalp)); case insensitive search  
(terpri)
; print (C 3)
(print(find 'c '((a 1) (b 2) (c 3)) :key #'car) )

Output

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

C 
(C 3)

find-if function

find-if function uses a predicate to search for an element, returns the first match. Returns false if element is not found.

Syntax

(find-if predicate list)

Arguments

  • predicate− predicate function to be tested. Predicate must accept one argument and should return t (true) or nil (false).

  • list− A list to be searched.

Returns

This function returns the first match, nil if not found.

Example - Using find-if to get first odd number

; prints 3
(print(find-if #'oddp '(2 4 6 3 7 8))); returns first odd number

Output

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

3

position function

position function searches for an element, returns the index of first match. Returns false if element is not found.

Syntax

(position element list)

Arguments

  • element− Element to search.

  • list− A list to be searched.

Returns

This function returns the index of first match, nil if not found.

Example - Using position to get index of matched element

; prints 2
(print(position 'c '(a b c d e)))  
(terpri)
; print nil as f is not present
(print(position 'f '(a b c d e))) 

Output

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

2
NIL

position-if function

position-if function accepts a predicate to search for an element, returns the index of first match. Returns false if element is not found.

Syntax

(position-if predicate list)

Arguments

  • predicate− predicate function to be tested. Predicate must accept one argument and should return t (true) or nil (false).

  • list− A list to be searched.

Returns

This function returns the index of first match, nil if not found.

Example - Using position to get index of matched element

; prints 4 
(print(position-if #'oddp '(2 4 6 8 7 9))); returns index of first odd number

Output

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

4
Advertisements