Lisp - Sequence Concatenation



Lisp provides concatenate function which is a very powerful function and can be used to concatenate lists, vectors and strings.

Syntax

(concatenate result-type sequences)

Arguments

  • result-type− Sequence type specifier, like 'list, 'vector and 'string.

  • sequences− Two or more sequnces to be concatenated.

Returns

This function returns a combined sequences containing all the elements of input sequences in the order provided.

Example - Concatenate Lists

We can combine lists and returns a list as specified by result-type argument as 'list.

main.lisp

; concatenate and get a combined list of two lists
(setf combinedList (concatenate 'list '(a b c) '(d e f)))

; print the concatenated list
(print (concatenate 'list combinedList '(g h i)))

Output

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

(A B C D E F G H I) 

Example - Concatenate List and Vector

We can combine a list with a vector and return a list as specified by result-type argument as 'list.

main.lisp

; concatenate a list with a vector
(setf combinedList (concatenate 'list '(a b c) #(d e f)))

; print the concatenated list
(print combinedList)

Output

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

(A B C D E F) 

Example - Concatenate Vectors

We can combine vectors and return a vector as specified by result-type argument as 'vector.

main.lisp

; concatenate a vector with a vector
(setf combinedVector (concatenate 'vector #(a b c) #(d e f)))

; print the concatenated vector
(print combinedVector)

Output

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

#(A B C D E F) 

Example - Concatenate Strings

We can use concatenate function to concatenate strings by specifying result-type argument as 'string.

main.lisp

; concatenate and print statement
(write-line (concatenate 'string "Hello, " "World!"))

Output

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

Hello, World!
Advertisements