Clojure中的部分应用

问题描述

您如何在Clojure中进行部分应用?

我尝试过:

(dorun (map println ["1" "2" "3" "4"]))

有效。

(async/send! channel "hello")

也可以。但是,如果我尝试申请部分申请

(dorun (map (async/send! channel) ["1" "2" "3" "4"]))

(dorun (map #(async/send! channel) ["1" "2" "3" "4"]))

(apply (partial map (async/send! channel) ["1" "2" "3" "4"]))

它说

clojure.lang.ArityException: Wrong number of args (1) passed to: immutant.web.async/send!

我在做什么错了?

解决方法

Clojure中的currying与ML,F#或Haskell等语言不同。

在Clojure中有2种方法可以进行部分应用:

  1. 进行闭合,您可以在其中指定参数的确切顺序:

    (fn [coll] (map str coll)) of #(map str %)

  2. 使用partial,它将按提供的顺序替换参数:

    (partial map str)

当您调用的函数的参数少于要求的数量时,您会得到ArityException(除非它是一个多函数函数,可以接受不同数量的参数)。

,

没关系,这似乎可行:

    (dorun (map (partial async/send! channel) ["1" "2" "3" "4"]))

有些困惑,为什么这不起作用

    (dorun (map #(async/send! channel) ["1" "2" "3" "4"]))