Changing map behaviour in Clojure

后端 未结 6 668
青春惊慌失措
青春惊慌失措 2020-12-20 18:50

I need to modify map function behavior to provide mapping not with minimum collection size but with maximum and use zero for missing elements.

Standard behavior:

6条回答
  •  一向
    一向 (楼主)
    2020-12-20 19:39

    Your method is concise, but inefficient (it calls count). A more efficient solution, which does not require the entirety of its input sequences to be stored in memory follows:

    (defn map-pad [f pad & colls]
      (lazy-seq
       (let [seqs (map seq colls)]
         (when (some identity seqs)
           (cons (apply f (map #(or (first %) pad) seqs))
                 (apply map-pad f pad (map rest seqs)))))))
    

    Used like this:

    user=> (map-pad + 0 [] [1] [1 1] (range 1 10))
    (3 3 3 4 5 6 7 8 9)
    

    Edit: Generalized map-pad to arbitrary arity.

提交回复
热议问题