- >宏和部分功能 [英] the -> macro and partial function

查看:154
本文介绍了 - >宏和部分功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我无法在 - >

的链接调用中使用部分函数或匿名函数

 ( - > 
123
seq
sort
reverse
(partial apply str))
=> #< core $ partial¥fn__4230 clojure.core$partial$fn__4230@335f63af>

我会认为部分函数会被创建并立即应用到上一个函数的结果,



使用一个参数的简单链接函数当然没有问题:

 ( - > 
123
seq
sort
reverse
clojure.string / join)


解决方案

- > - >> 只是宏,您可以测试 - > > macroexpand-1 (请注意报价')

  user => (macroexpand-1'( - > 
123
seq
sort
reverse
(partial apply str)))

(partial(reverse(sort(seq123)))apply str)

获取函数而不是字符串 - 结果是从 reverse 返回的一部分collection(这是一个函数)apply str 作为参数。



如果由于某种原因需要在 > ,您应该将其包装在括号中:

  user => (macroexpand-1'( - > 
123
((partial sort));我们加上括号so - > have plase来插入
))
(部分排序)123)

或者您可以使用 - & > 宏,因为它在此处执行与 partial 相同的工作:

 ((partial strhello)world)

hello world

 ( - >>(strhello)world );展开为(strhelloworld)

hello world


Why can't I use a partial function or an anonymous function in a chained call with ->?

(->
    "123"
    seq
    sort
    reverse
    (partial apply str))
=> #<core$partial$fn__4230 clojure.core$partial$fn__4230@335f63af>

I would have thought the partial function would be created and immediately applied to the previous function's result, but it's actually returned itself.

A simple chaining of functions with one parameter of course works without problems:

(->
    "123"
    seq
    sort
    reverse
    clojure.string/join)

解决方案

As -> and ->> are just macros, you can test what -> expands to with macroexpand-1 (note the quote ')

user=> (macroexpand-1 '(->
       "123"
       seq
       sort
       reverse
       (partial apply str)))

(partial (reverse (sort (seq "123"))) apply str)

So that's why you get a function instead of a string - result is partial of collection (which is a function) returned from reverse and apply str as arguments.

If for some reason you need to apply a funcion in ->, you should wrap it in parens:

user=> (macroexpand-1 '(->
    "123"
    ((partial sort))  ; we add parens around so -> have plase to insert
   ))
((partial sort) "123")

Or you can use ->> macro, as it is doing same work as partial here:

((partial str "hello ") "world")

"hello world"

and

(->> (str "hello ") "world")    ; expands to (str "hello " "world")

"hello world"

这篇关于 - >宏和部分功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆