如何在Groovy中为功能/方法创建功能管道? [英] How to create functional pipes for functions/methods in Groovy?

查看:106
本文介绍了如何在Groovy中为功能/方法创建功能管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建管道来连接Groovy函数(方法)调用,就像在其他功能语言(例如F#)中所做的那样:

I want to create pipes to connect Groovy function (method) calls like its done in other functional languages, such as F#:

 let print message =
     printf "%s" message

 // "Hello World" will be passed as a parameter to the print function
 "Hello World" |> print

使用or运算符有一个简单的实现:

There is a naive implementation using the or operator:

Object.metaClass.or { it -> it(delegate)}

def print = { msg ->
    println msg
}

"Hello World" | print      //Hello World

但是它仅适用于带有1个参数的函数.要获取更多参数,必须使用rcurry:

But it only works for functions with 1 parameter. For more parameters, rcurry has to be used:

Object.metaClass.or { it -> it(delegate)}

def print = { msg1, msg2 ->
    println msg1 + msg2
}

"Hello World" | print.rcurry('!!!')   //Hello World!!!

是否有办法摆脱rcurry方法并使Groovy代码更类似于F#?顺便说一句,这个幼稚的实现仅适用于Groovy脚本文件.如何使它也适用于班级文件?

Is there a way to get rid of the rcurry method and make the Groovy code more similar to F#'s? BTW, this naive implementation only works for Groovy script files. How do I make it work also for class files?

注意:还有其他关于Groovy中管道的问题,但是这些都是关于shell命令而不是功能的管道.

Notice: There are other questions about pipes in Groovy but these are about pipes for shell commands not functions.

推荐答案

您似乎只想with并使用.&将方法转换为Closures,并使用>>进行函数组合.

It looks like you just want with and using .& to convert methods to Closures, and >> for function composition.

public static String addExclamations(String s) { 
    return s + "!!!"
} 

Closure printUppercase = { String s -> println s.toUpperCase() }

"Hello World".with (this.&addExclamations >> printUppercase)

一个真实的例子,我发现自己一直在使用:

A real world example I find myself using all the time:

import groovy.json.JsonOutput

[a:[b:'c', d:'e']].with (JsonOutput.&toJson >> JsonOutput.&prettyPrint)        

我不确定您对多参数的处理方式是什么,因为各种curry解决方案对我来说似乎都是明智的,但是您已经忽略了……也许我可以编辑此答案,如果可以一个如何显示外观的示例?

I'm not sure what you're getting at with the multiparameter stuff, because the various curry solutions seem sensible to me, but you've dismissed that... perhaps I can edit this answer if you can give an example of how you would like it to look?

这篇关于如何在Groovy中为功能/方法创建功能管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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