Wuffle
Wuffle

Reputation: 83

Clojure Passing Individual Variables to Function

I am trying to pass some vectors containing a list of nodes in to a function in clojure the function works if i was to type the variables in but i am not sure how to pass a single variable from each vector in at a time.

(def ItemPickUp [:a1 :Mail])
(def ItemDestinations [:Storage :a1])
(def Robot {[ItemPickUp] [ItemDestinations]})



(defn shortestPath [g start dest]
(let [not-destination? (fn [[vertex _]] (not= vertex dest))]
(-> (shortest-paths g start)
    (->> (drop-while not-destination?))
    first
    (nth 2))))

(apply shortestPath G (apply first Robot)((apply second Robot)))

I need to pass a variable from the ItemPickUp and ItemDestination into shortestPath using robot but instead of passing one of the variable in it passes both :a1 and :Mail and vice versa for the other one.

How do i go about passing each variable in individually so the first two variables for the first iteration is :a1 and :Storage and so on?

Thanks.

Upvotes: 1

Views: 152

Answers (2)

K. Cherkashin
K. Cherkashin

Reputation: 41

In case of (def Robot [[ItemPickUp] [ItemDestinations]]) and you want to use it you can do:

(apply map (partial shortestPath G) Robot)

Apply in this case will reduce to:

(map (partial shortestPath G) (first Robot) (second Robot))

and of course will throw ArityException if Robot has other than two elements.

You can think about apply as moving parentheses (function call) to his first argument and taking out parentheses from last argument (if some).

Upvotes: 0

Magos
Magos

Reputation: 3014

In Clojure this is normally done with map - it takes a function f and any number of collections and lazily produces a sequence of (f (first coll1) (first coll2)...), (f (second coll1) (second coll2)...)...
So it should just be

(map (partial shortestPath G) ItemPickup ItemDestinations)

(Some other functional languages distinguish one-collection mapping from multi-collection zipping - I believe Haskell is influential here. It needs this because its functions have fixed arities, so you have zipWith,zipWith3 etc. Having the parenteses to indicate number of arguments means Lisps don't have to deal with that.)

Upvotes: 1

Related Questions