Search code examples
javaclojurefunctional-programming

Iterating function arguments in Clojure


I am having trouble iterating over the function arguments passed in to the following function.

(defn iterateDates
  [& dates]
  (let [ukFormatter (java.time.format.DateTimeFormatter/ofPattern "dd-MM-yyyy")]
    (for [i [dates]]
      (java.time.LocalDate/parse i ukFormatter))))

(iterateDates "09-10-2019" "10-10-2019" "11-10-2019")

This however when called, returns the following error:

Error printing return value (ClassCastException) at clojure.core/getOldestDate$iter$fn$fn (core.clj:96).
clojure.lang.ArraySeq cannot be cast to java.lang.CharSequence

I am not sure on how to iterate over the arguments passed in and take each element as a separate value which can then be passed to another function.

My goal ultimately with the code will be to compare a list of dates and find the oldest date in there. This code just tries to parse each argument as a date.


Solution

  • (defn iterateDates
      [& dates]
      (let [ukFormatter (java.time.format.DateTimeFormatter/ofPattern "dd-MM-yyyy")]
        (for [i dates]
          (java.time.LocalDate/parse i ukFormatter))))
    
    (iterateDates "09-10-2019" "10-10-2019" "11-10-2019")
    

    This version should work.

    You wrote (for [i [dates]] in your original code, and it worked as you unintentionally specified:

    1. It used a vector [] of dates for iteration, where dates is already a sequence.
    2. The first element of this vector is the dates, which is an AraySeq.
    3. java.time.LocalDate/parse tried to parse ArraySeq as a CharSequence and failed.