Standard version or idiomatic use of (fn [f & args] (apply f args))

后端 未结 8 1847
南旧
南旧 2021-01-17 12:37

Every so often I find myself wanting to apply a collection of functions on several collections of parameters. It\'s easy to do with map and a very simple function.



        
8条回答
  •  一向
    一向 (楼主)
    2021-01-17 13:37

    If you really don't have a clue about the function name, but you know what the in- and output have to be, you can try https://github.com/Raynes/findfn.

    (find-arg [-1 6 27] map '% [- + *] [1 2 3] [1 2 3] [1 2 3])
    ;=> (clojure.core/trampoline)
    

    This tells us that

    (map trampoline [- + *] [1 2 3] [1 2 3] [1 2 3])
    ;=> (-1 6 27)
    

    Actually, you can abuse trampoline as funcall in clojure. But it is hardly idiomatic, because it is a Lisp-1. The above code evaluates to:

    [(trampoline - 1 1 1), (trampoline + 2 2 2), (trampoline * 3 3 3)] which then becomes [-1 6 27] (in the form a of lazyseq to be precise).

    As Adrian Mouat points out in the comment below, this probably isn't the preferred way to solve it. Using a funcall like construct smells a bit funny. There must be a cleaner solution. Until you've found that one, findfn can be helpful ;-).

提交回复
热议问题