Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

clojure sequence
split-at method
communitycreator

The split-at method in Clojure

Chinweuba Elijah Azubuike

Overview

The split-at method in Clojure splits a sequence into two sequences and returns them. It can be used to split large sequences into smaller sequences. An argument is passed to split-at, which specifies where the input sequence will be split. A Clojure sequence is a data storage structure that holds a collection of data objects. It can be seen as a logical list. The seq method is used to build a sequence.

Syntax

(split-at number seqq)
In this example, 'seqq' will be split at 'number'.

Parameters

The split-at method accepts two input arguments.

  • seqq: This represents the sequence that is being split.
  • number: The index of the sequence at which the split will occur.

Return value

The method will return all elements to the left of the element at number in the first sequence and all elements to the right of the element at number (including the element at number) in the second sequence.

Let’s look at an example.

Example

(ns clojure.examples.example
   (:gen-class))
(defn func []
   (def seq1 (seq [1 2 8 9 1 0 6 8 2]))
   (println (split-at 1 seq1)))
(func)
Hit run to see the results. Please observe that there are two output sequences. Try changing the values of the first argument being passed to 'split at', hit run again, and observe the results.

Explanation

  • Line 3: We define a function func.
  • Line 4: We define our sequence seq1 using seq.
  • Line 5: We use the split-at method to split the sequence seq1 at 1. We can observe that the first output sequence contains one element, and the second contains the rest.
  • Line 6: We call our defined function func.

RELATED TAGS

clojure sequence
split-at method
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring