Clojure Passing Individual Variables to Function

元气小坏坏 提交于 2019-12-11 13:43:27

问题


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.


回答1:


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.)




回答2:


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).



来源:https://stackoverflow.com/questions/36367877/clojure-passing-individual-variables-to-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!