liveBook · Manning

Second

As explained in Clojure: The Essential Reference

fnext is a Clojure function that returns the second element of a sequence or nil when it is unavailable.

`second` returns the second item of a seqable collection. `fnext` does the same thing: it takes the first item of `(next coll)`. Both return `nil` for `nil`, an empty collection, or a collection with fewer than two items. A second item whose value is `nil` also produces `nil`. section 3.5.1 section 10.1

Select a value from each record

`(second '(1 2 3 4))` and `(fnext '(1 2 3 4))` both return `2`. When records hold a location followed by a temperature, `(sort-by second > records)` sorts by that temperature; `first` then selects the record with the highest value. section 3.5.1 section 10.1

Position depends on the collection’s sequence order. A hash map yields key-value pairs, while hash maps and sets do not guarantee insertion order for `second`. Use it when the second position is meaningful, not to retrieve a particular map entry or set member. section 3.5.1

(def message [["A" 1 28] ["H" 37 82 11] ["N" 127 0]]) ; #1

(defn process [message] ; #2
  (lazy-seq
    (when-let [xs (seq message)]
      (let [e1 (ffirst xs) e2 (fnext xs)] ; #3
        (cons (if (nil? e2)
                {:item e1 :succ :incomplete}
                {:item e1 :succ e2})
          (process (rest xs)))))))

(process message) ; #4
;; ({:item "A", :succ ["H" 37 82 11]}
;;  {:item "H", :succ ["N" 127 0]}
;;  {:item "N", :succ :incomplete})

An adjacent-record processor uses `fnext` to get the next record, or `nil` when the current record is last. section 10.1

How Clojure: The Essential Reference covers it

How deep it goes
Defines the one-argument contract, nil cases, and collection-order caveat; identifies `fnext` as first-of-next without examining implementation internals.
Examples
Uses a number list, temperature records sorted by their second item, and adjacent records processed with `fnext`.
What it assumes
Assumes familiarity with Clojure collections and function calls while defining the required seqable input and nil return behavior.
What you can do after
Apply it via Clojure’s `second` or `fnext` to read a second item while accounting for missing items and unordered collections.
How it connects
Relates second to `first`, `next`, `fnext`, `sort-by`, and seqable collections.

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.