Scala 传递函数序列作为参数类型
Scala Passing Sequence of Functions as Argument Type
为了流水线处理各种数据转换函数,我想遍历一系列函数并将每个函数应用于初始输入。对于单个输入,它将是这样的:
def transformPipeline(f: MyType => MyType)(val: MyType): MyType = {...}
我如何定义这个函数,而不是接受单个 f: MyType => MyType
它会接受类似 Seq(f: MyType => MyType)
的东西
例如
def transformPipeline(f: Seq[MyType => MyType])(val: MyType): MyType = {...}
如果我对你的问题的理解正确,那么这可能就是你想要的。
def transformPipeline(fs: Seq[MyType => MyType])(init: MyType): MyType =
fs.foldLeft(init)((v, f) => f(v))
测试如下:
type MyType = Int
transformPipeline(Seq(_+1,_*2,_/3))(17) //res0: MyType = 12
为了流水线处理各种数据转换函数,我想遍历一系列函数并将每个函数应用于初始输入。对于单个输入,它将是这样的:
def transformPipeline(f: MyType => MyType)(val: MyType): MyType = {...}
我如何定义这个函数,而不是接受单个 f: MyType => MyType
它会接受类似 Seq(f: MyType => MyType)
例如
def transformPipeline(f: Seq[MyType => MyType])(val: MyType): MyType = {...}
如果我对你的问题的理解正确,那么这可能就是你想要的。
def transformPipeline(fs: Seq[MyType => MyType])(init: MyType): MyType =
fs.foldLeft(init)((v, f) => f(v))
测试如下:
type MyType = Int
transformPipeline(Seq(_+1,_*2,_/3))(17) //res0: MyType = 12