Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between seq and seq?

Tags:

clojure

-------------------------
clojure.core/seq
([coll])
  Returns a seq on the collection. If the collection is
    empty, returns nil.  (seq nil) returns nil. seq also works on
    Strings, native Java arrays (of reference types) and any objects
    that implement Iterable.
-------------------------
clojure.core/seq?
([x])
  Return true if x implements ISeq
-----

Obviously empty? is based on seq. what is the difference between empty? and nil? I'm soooo confused.

clojure.core/empty?
([coll])
  Returns true if coll has no items - same as (not (seq coll)).
  Please use the idiom (seq x) rather than (not (empty? x))

And more:

(not (seq? ())) ;;false
(not (seq ())) ;;true
(not nil) ;;true
like image 534
lkahtz Avatar asked Dec 22 '22 02:12

lkahtz


1 Answers

  • seq converts collection to sequence and returns nil if the collection is empty; also returns nil if the argument is nil.
  • seq? returns true if the argument is a sequence (implements the ISeq interface).
  • empty? will return true if the argument is either nil or an empty collection.
  • nil? will return true if the argument is nil.

I guess the bit about the (seq x) idiom in the docstring for empty? applies to common practice of using if-let like so:

(defn print-odd-numbers [coll]
  (if-let [x (seq (filter odd? coll))]
    (println "Odd numbers:" x)
    (println "No odd numbers found.")))
like image 63
MisterMetaphor Avatar answered Jan 02 '23 01:01

MisterMetaphor