Lisp - Sequence SubSequence
Lisp provides multiple functions to get subsequnce of a various type of sequence like list, vectors and strings. Here are the commonly used functions explained with examples.
subseq function
subseq function extracts a subsequence from a sequence.
Syntax
(subseq sequence startIndex [endIndex])
Arguments
sequence− A sequnce whose subsequnce is to be retrieved.
startIndex− start index from which SubSequence is to be retrieved.
endIndex− an optional end index upto which subsequence is to be retrieved. endIndex is excluded.
Returns
This function returns a new sequence containing the resulted subsequnce.
Example
; prints subsequence (B C D) (print(subseq '(a b c d e) 1 4)) (terpri) ; print substring "point" (write-line(subseq "tutorialspoint" 9))
Output
When you execute the code, it returns the following result −
(B C D) point
copy-seq function
copy-seq function creates copy of the sequence. It is useful when we want to modify the sequence without altering the original sequnce.
Syntax
(copy-seq sequence)
Arguments
sequence− A sequnce whose copy is to be retrieved.
Returns
This function returns a new sequence as a copy of sequence.
Example
; prints list (print(copy-seq '(a b c d e)))
Output
When you execute the code, it returns the following result −
(A B C D E)
elt function
elt function accesses an element at particular index in a sequence. Index starts from zero.
Syntax
(elt sequence index)
Arguments
sequence− A sequnce whose element is to be retrieved.
index− A non-negative index. Index starts from zero and should be less than total number of elements in a sequence.
Returns
This function returns element at particular index of the sequence.
Example
; prints C (print(elt '(a b c d e) 2)) (terpri) ; prints #\h (print(elt "hello" 0))
Output
When you execute the code, it returns the following result −
C #\h