首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Scala函数与泛型的组合

Scala函数与泛型的组合
EN

Stack Overflow用户
提问于 2014-11-06 05:22:30
回答 2查看 162关注 0票数 0

我想用andThen将2个Scala函数组合成第三个函数,但是类型系统遇到了问题。

以下是代码:

代码语言:javascript
运行
复制
object Test{

  def process1[T](in : List[T]) : List[T] = in

  def process2[T](in : List[T]) : List[T] = in

  //this works fine but you have to read it inside out
  def combined2[T](in : List[T]) : List[T] = process2(process1(in))

  //this also works but at the cost of creating a new function every time
  def combined3[T](in : List[T]) : List[T] = {
    (process1[T] _ andThen process2[T] _)(in)
  }

  //this doesn't work. it is a function List[Nothing] => List[Nothing]
  val combined = process1 _ andThen process2 _

  def main(s : Array[String]) {
    val input : List[Int] = List(1,2,3)
    val out1 : List[Int] = process1(input)

    val combinedOut2 : List[Int] = combined2(input)

    val combinedOut3 : List[Int] = combined3(input)

    //this will not compile as combined is [List[Nothing] => List[Nothing]
    //val combinedOut : List[Int] = combined(input)
  }
}

是否有一种很好的方法可以将combined的值从List[T]转换为List[T],或者这是类型擦除的一个基本问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-06 12:51:49

不确定它是否不错,但可以将combined3缩短为:

代码语言:javascript
运行
复制
def combined3[T] = process1[T] _ andThen process2[T] _

每次创建函数实例都可以针对每种情况进行优化:

代码语言:javascript
运行
复制
val combinedInt = combined3[Int]

combinedInt(input)
票数 1
EN

Stack Overflow用户

发布于 2016-04-16 06:22:09

你可以用这种方式组合功能,它更干净

代码语言:javascript
运行
复制
implicit class FunctionCombiner[T, U](fn: T => U) {
    def &&&(f: T => U): T => U = {
        (t: T) => {
            fn(t); f(t)
        }
    }
}

在此之后,您可以运行如下语句:

代码语言:javascript
运行
复制
val f1 = (i: Int) => println((1*i).toString)
val f2 = (i: Int) => println((2*i).toString)
val f3 = (i: Int) => println((3*i).toString)

val f = f1 &&& f2 &&& f3

f(5)

这就产生了结果:

代码语言:javascript
运行
复制
5
10
15
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26772270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档