Scala中函数组合的简洁语法? [英] Concise syntax for function composition in Scala?

查看:64
本文介绍了Scala中函数组合的简洁语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Scala并执行以下任务-如果字符串为空,则返回null,否则返回大写.

I'm learning Scala and ran across the following task - if string is blank then return null, otherwise uppercase it.

Apache Commons中有两个函数组合在一起可以解决此问题.在Haskell中,我只写:

There are two functions in Apache Commons that composed together solves the problem. In Haskell I'd just write:

upperCaseOrNull = StringUtils.stripToNull . StringUtils.upperCase

但是我找不到在Scala中进行简单干净的函数合成的方法.我发现的最短方法如下:

However I can't find a way to do an easy and clean function composition in Scala. the shortest way I found is as follows:

def upperCaseOrNull (string:String) = StringUtils.stripToNull (StringUtils.upperCase(string))
def upperCaseOrNull = StringUtils.stripToNull _ compose StringUtils.upperCase _

Scala是否提供了更简洁的语法,可能没有所有下划线?

Does Scala offer a more concise syntax, possibly without all those underscores?

推荐答案

Haskell对于某些真正关心的事情非常精巧.因此,几乎是不可能击败的.如果您执行了太多的函数组合操作,以至于开销确实受到了阻碍(就个人而言,重复StringUtils.会给我带来很多麻烦!),您可以执行类似

Haskell is a master of extreme compactness for a few things it really cares about. So it's pretty much impossible to beat. If you are doing so much function composition that the overhead really gets in your way (personally, I'd be a lot more troubled by repeating StringUtils.!), you can do something like

implicit class JoinFunctionsCompactly[B,C](g: B => C) {
  def o[A](f: A => B) = g compose f
}

因此,现在Haskell上只有四个额外的字符(两次_).

so now you only have four extra characters (_ twice) over Haskell.

这篇关于Scala中函数组合的简洁语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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