使用 Clojure 进行函数式编程

发布于 2024-12-12 05:10:32 字数 349 浏览 0 评论 0原文

大师

这里有一个问题要问你:我正在开发一个 clojure 程序, 涉及将函数传递给函数。

我有这样的事情:

(defn funct-op [args]
      ((first args) 
       (second args) 
       (last args)   )

(funct-op '(+ 2 2))

我怎样才能哄骗funct-op给我4而不是我的2 目前得到?我可能需要将函数传递给宏作为我的 项目取得进展。关于如何做到这一点有什么建议吗?感谢您的帮助!

gurus

Here's a question for you: I am working on a clojure program that
involves passing functions to functions.

I have something like:

(defn funct-op [args]
      ((first args) 
       (second args) 
       (last args)   )

(funct-op '(+ 2 2))

How can I coax funct-op into giving me 4 rather than the 2 I am
currently getting? I may need to pass a function to a macro as my
project progresses. Any tips on how to do that? Thanks for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

傲影 2024-12-19 05:10:32

为了将“+”转换为函数,您可以使用resolve。这应该适用于核心函数,但您可能需要 ns-resolve 来实现自定义函数。然后,您可以使用 apply 将其余参数传递给该函数。

(defn funct-add [args] (apply (resolve (first args)) (rest args)))

不确定您的最终目标是什么,但我认为这就是您正在寻找的答案。

In order to turn the '+' into a function you can use resolve. This should work on core functions, but you may need ns-resolve for custom functions. You can then use apply to pass the rest of the arguments to that function.

(defn funct-add [args] (apply (resolve (first args)) (rest args)))

Not sure what your end goal really is but I think that is the answer you were looking for.

尬尬 2024-12-19 05:10:32

funct-add 到底应该做什么?如果是 (funct-add '(- 2 2)) 怎么办?

无论如何,请考虑申请,即使已经结束:

(defn apply-wrapper [args]
   (apply (first args) (rest args)))

; note use of of the [...] form
(apply-wrapper [+ 2 2]) ; => 4
(apply-wrapper [- 2 2]) ; => 0

比较这些形式可能会有所启发:

(+ 1 2)   ; 3
'(+ 1 2)  ; (+ 1 2)
[+ 1 2]   ; [#<core$_PLUS_ clojure.core$_PLUS_@a8bf33> 1 2]

注意最后一个形式是如何评估的;它不仅仅是一个“文字列表”——不再有符号了! :-)

快乐编码。

What is funct-add really supposed to do? What if it was (funct-add '(- 2 2))?

Anyway, consider apply, even wrapped up:

(defn apply-wrapper [args]
   (apply (first args) (rest args)))

; note use of of the [...] form
(apply-wrapper [+ 2 2]) ; => 4
(apply-wrapper [- 2 2]) ; => 0

Comparing these forms may be enlightening:

(+ 1 2)   ; 3
'(+ 1 2)  ; (+ 1 2)
[+ 1 2]   ; [#<core$_PLUS_ clojure.core$_PLUS_@a8bf33> 1 2]

Note how the last one was evaluated; it is not just a "literal list" -- no symbol there anymore! :-)

Happy coding.

芸娘子的小脾气 2024-12-19 05:10:32

我不确定,这些东西?

(defn funct-op [f list]
  (apply f list))

(funct-op + '(1 2));=>3

I'm not sure, these things?

(defn funct-op [f list]
  (apply f list))

(funct-op + '(1 2));=>3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文