Lisp - Searching in Sequence
Lisp provides various functions to find an element in a sequence. Each function has its own merits. 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 sequence)
Arguments
element− Element to search.
sequence− A sequnce to be searched.
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))) (terpri) ; print nil as f is not present (print(find 'f '(a b c d e)))
Output
When you execute the code, it returns the following result −
C NIL
Example - Using find to get T/Nil for search result
find returns the matched element. We can negate the result twice to get T or Nil for a search result as shown below −
; prints C (print(not(not(find 'c '(a b c d e))))) (terpri) ; print nil as f is not present (print(not(not(find 'f '(a b c d e)))))
Output
When you execute the code, it returns the following result −
T NIL
position function
position function searches for an element, returns the index of first match. Returns false if element is not found.
Syntax
(position element sequence)
Arguments
element− Element to search.
sequence− A sequnce 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
count function
count function returns the occurences of an element. Returns zero if element is not found.
Syntax
(count element sequence)
Arguments
element− Element to searched.
sequence− A sequnce to be searched.
Returns
This function returns the occurences of element in the list.
Example - Using count to get occurences matched element
; prints 3 (print(count 'c '(a b c c c))) (terpri) ; print 0 as f is not present (print(count 'f '(a b c d e)))
Output
When you execute the code, it returns the following result −
3 0