How to convert between list types in Clojure

In Clojure's ecosystem, the into command allows us to put anything sequable (defined as a sequence) into an empty container (list, vector, map, set, and sorted-map). This command extends the conj command which implements the base abstraction for inserting entries into a collection based on its type.

Clojure is built on the composable abstractions concept, which makes the following abstraction flow smoother:

Abstraction flow
Abstraction flow

Let's dive into some examples to better assimilate the capabilities of this command.

Example

This example shows how to convert a lazy list into a vector:

(def l (take 10 (filter odd? (range 0 100))))
(print "Converting a lazy list", l , "into a vector:")
(print (into [] l))

Explanation

  • Line 1: Defines a lazy list composed of the first 10 odd numbers extracted out of a range from 0 to 100.

  • Line 2: Prints out an informative message about the action to be performed.

  • Line 3: Invokes the into command in order to convert the lazy list l into a vector and print out the output returned.

Example

The following example demonstrates how to convert a vector into a set:

(def v [10 20 30 40])
(print "Converting a vector" , v , "into a set:")
(print (into #{} v))

Explanation

  • Line 1: Devises a vector and stores it in a variable named v.

  • Line 2: Prints out an informative message about the action to be performed.

  • Line 3: Invokes the into command in order to convert the vector v into a set and prints out the output returned.

Example

The following example illustrates how to convert a set of vectors into a map:

(def sv #{[10 20] [30 40]})
(print "Converting a set of vectors" , sv , "into a map:")
(print (into {} sv))

Explanation

  • Line 1: Defines a set of vectors and stores it in a variable called sv.

  • Line 2: Prints out an informative message about the action to be performed.

  • Line 3: Calls the into command to convert the set of vectors sv into a map, and prints out the output returned.

Example

This example explains how to convert a vector of maps into a set of maps:

(def vm [{10 20} {30 40}])
(print "Converting a vector of maps" , vm , "into a set of maps:")
(print (into #{} vm))

Explanation

  • Line 1: Defines a vector of maps and stores it in a variable called vm.

  • Line 2: Prints out an informative message about the action to be performed.

  • Line 3: Calls the into command to convert the vector of maps vm into a set of maps, and prints out the output returned.

Copyright ©2024 Educative, Inc. All rights reserved