I've been using the Rosalind problems to learn clojure and the code below is part of a solution for the mortal rabbits problem. My solution was to create a record called rabbit that would keep track of each rabbit. The rabbit record would be stored in a vector and I would loop over the months and at each month update the vector by adding new rabbits (add-rabbits
) and filtering the dead ones (remove-rabbits
).
This sounds straightforward enough but I have run into a problem that I can't seem to wiggle around: when I try to pass the updated vector back into the loop I run into an error and I'm looking to figure out whats going on. I'm sure its one of those errors that I'll back on and it will be super obvious but hey, thats what happens with a new language right? Any insights would be appreciated.
;define a rabbit record with birth and death months
(defrecord rabbit [born dies] )
; function that calculates number of living rabbits
(defn iter-rabbit2 [months lifemonths]
(letfn [ (add-rabbits [month rabbits]
;add-rabbits looks for reproductively active rabbits and creates new rabbits
(let [num-repr-rabbits (count (filter #(>= (+ month 1) (.born %)) rabbits))
new-rabbits (vec (repeat num-repr-rabbits (rabbit. (+ month 1) (+ month lifemonths 1))))]
(do
(println "rabbits" rabbits) ; for debugging
(println "rabbits type " (type rabbits))
(if (seq new-rabbits)
(apply conj (vec rabbits) (vec new-rabbits))
(rabbits)))))
(remove-rabbits [month rabbits]
;remove rabbits filters the rabbits vector of dying rabbits
(let [livingrabbits (vec (filter #(not= month (.dies %)) rabbits ))]
(do
(println "remove rabbits rabbits" livingrabbits) ;for debugging
(println (type livingrabbits))
(livingrabbits)))) ]
(loop [month 0
lifemonth lifemonths
rabbits [(rabbit. month lifemonth)] ]
(if (= month months)
[rabbits]
(recur (+ month 1)
(+ lifemonth 1)
( ->> rabbits
(add-rabbits month)
(remove-rabbits month)
(apply vector)
))))))
(iter-rabbit2 5 6)
The error i am getting is the following:
ArityException Wrong number of args (0) passed to: PersistentVector
clojure.lang.AFn.throwArity (AFn.java:437)