Scala 高阶函数的Case类方法
我正在尝试删除代码中的冗余。我想我可以用高阶函数来做 我要做的是将公共位分解成f3,然后将f1和f2之间不同的位作为传递到f3的参数Scala 高阶函数的Case类方法,scala,higher-order-functions,abstraction,case-class,Scala,Higher Order Functions,Abstraction,Case Class,我正在尝试删除代码中的冗余。我想我可以用高阶函数来做 我要做的是将公共位分解成f3,然后将f1和f2之间不同的位作为传递到f3的参数 object Example extends App { case class action(name: String, age: Int) { def setName(new_name: String): action = this.copy(name = new_name) def setAge(new_age: Int): action
object Example extends App {
case class action(name: String, age: Int) {
def setName(new_name: String): action = this.copy(name = new_name)
def setAge(new_age: Int): action = this.copy(age = new_age)
}
def f1(x: action, increment: Int) = {
// big block of code which does a....
// a single line in the block calling
val older_person = x setAge (x.age + increment)
// big block of code which does b....
}
def f2(x: action, new_name: String) = {
// big block of code which does a....
// a single line in the block calling
val new_name_person = x setName new_name
// big block of code which does b....
}
/* Now as there is clearly a redundancy, which can be solved by higher order functions.
I want to combine f1 and f2 into a single function. The function will take in the action, the value, and the
function to apply. It will then call the relevant function inside the method.
*/
def f3[T](x: action)(f: T => action)(value: T) = {
// big block of code which does a....
// call x.f(value)
val new_action = ???
// big block of code which does b....
}
// then in my code I can call like this:
// f3(x)(setAge)(100)
// f3(x)(setName("new_name")
}
我所困惑的是,我如何才能在case类中传递一个方法函数?还有什么方法可以优雅地执行此操作吗?在
f3
中,您可以简单地接受Action=>Action
类型的函数(我将使用Action
而不是Action
,以减少混淆)
然后,您可以定义一些有用的函数,并使用currying使它们更易于以后使用:
object Action {
def setName(name: String)(action: Action) = action.copy(name=name)
def incAge(inc: Int)(action: Action) = action.copy(age=action.age+inc)
}
然后像这样使用它:
val x = Action("Foo", 42)
f3(x)(Action.incAge(100))
f3(x)(Action.setName("new_name"))
在
f3
中,您可以简单地接受类型为Action=>Action
的函数(我将使用Action
而不是Action
,以减少混淆)
然后,您可以定义一些有用的函数,并使用currying使它们更易于以后使用:
object Action {
def setName(name: String)(action: Action) = action.copy(name=name)
def incAge(inc: Int)(action: Action) = action.copy(age=action.age+inc)
}
然后像这样使用它:
val x = Action("Foo", 42)
f3(x)(Action.incAge(100))
f3(x)(Action.setName("new_name"))