Changing map behaviour in Clojure

后端 未结 6 678
青春惊慌失措
青春惊慌失措 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:33

    Along the lines of @LeNsTR's solution, but simpler and faster:

    (defn map-ext [f & colls]
      (lazy-seq
       (let [colls (filter seq colls)
             firsts (map first colls)
             rests (map rest colls)]
        (when (seq colls)
          (cons (apply f firsts) (apply map-ext f rests))))))
    
    (map-ext + [1 2 3] [4] [5 6] [7 8 9 10])
    ;(17 16 12 10)
    

    I've just noticed Michał Marczyk's accepted solution, which is superior: it deals properly with asymmetric mapping functions such as -.

提交回复
热议问题