地图,在朱莉娅用`|>`减少

can*_*his 12 julia

在R中,dyplr您拥有%>%允许您将函数输出传递给新函数的运算符,从而无需存储中间值.在julia中,您可以通过使用|>运算符实现非常相似的功能.

用法示例

2 |> log |> sqrt 
Run Code Online (Sandbox Code Playgroud)

对我而言,这比阅读更好sqrt(log(2)).特别是当链条变得很长时.我想用这个语法,但也对map,reduce型功能朱莉娅.

建立

from = "abcdefghijklmnopqrstuvwxyz"
to   = "cdefghijklmnopqrstuvwxyzab"
trans = "g fmnc wms bgblr rpylqjyrc gr zw fylb <>"
d = {from[i] => to[i] for i = 1:26}
d[' '] = ' '
Run Code Online (Sandbox Code Playgroud)

什么有效

map(x -> d[x], filter(x -> isalpha(x) || isspace(x), trans))
Run Code Online (Sandbox Code Playgroud)

这样可行,但它读起来并不像我希望的那样好.另一种方法是将中间结果存储到变量中,但这似乎也很冗长:

res1 = filter(x -> isalpha(x) || isspace(x), trans)
map(x -> d[x], res1)
Run Code Online (Sandbox Code Playgroud)

我更喜欢什么

R语法与此类似:

trans |> 
  filter(x -> isalpha(x) || isspace(x)) |> 
  map(x -> d[x])
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为在Julia中,映射/过滤器函数在迭代之前.R会通过给你一个.你可以使用的中缀来解决这个问题,在这种情况下语法看起来会更像:

trans |> 
  filter(x -> isalpha(x) || isspace(x), .) |> 
  map(x -> d[x], .)
Run Code Online (Sandbox Code Playgroud)

朱莉娅有可能这样吗?该|>操作员必须的代码长链清理到操作整齐管道的潜力.也许更接近问题的Julia-thonic方式也可以被认为是这个问题的答案.

ric*_*2hs 11

不完全确定你在寻找什么,但是:

SPOILER ALERT 8-)

julia> trans |> 
         t -> filter(x -> isalpha(x) || isspace(x), t) |> 
         f -> map(x -> d[x],f)
"i hope you didnt translate it by hand "
Run Code Online (Sandbox Code Playgroud)


Mat*_* B. 7

您还可以使用Lazy包中的@as宏来更接近您的首选表单:

julia> using Lazy

julia> @as _ trans begin
         filter(x -> isalpha(x) || isspace(x), _)
         map(x -> d[x], _)
       end
"i hope you didnt translate it by hand "
Run Code Online (Sandbox Code Playgroud)