What is the cons() method in Clojure?

Overview

A list is a data storage structure that holds a collection of data objects. The list() method in Clojure builds lists. You can read this shot about creating a list.

The cons() method is a list method that adds a data item to a list and returns a new list.

Syntax

(cons element lst)

Parameter

We pass two parameters to the cons() method:

lst: This represents the list of items.

element: This represents the data items to be added.

Return value

The cons method will return a list of data items.

Example

(ns clojure.examples.example
(:gen-class))
(defn Conss []
(println (cons 6 (list 11, 54,9))))
(Conss)

Explanation

  • Line 3: We define a function, Conss.

  • Line 4: We print the new list returned using println. The cons method adds data item 6 to the list.

  • Line 5: We call the Conjj function.

Free Resources