【发布时间】:2012-04-01 15:00:21
【问题描述】:
假设我有一个包含两个列表的特征。有时我对一个感兴趣,有时对另一个感兴趣。
trait ListHolder {
val listOne = List("foo", "bar")
val listTwo = List("bat", "baz")
}
我有一个函数调用链,在它的顶部我有我需要在列表之间选择的上下文,但在它的底部我使用特征。
在命令式范式中,我通过函数传递上下文:
class Imperative extends Object with ListHolder {
def activeList(choice : Int) : List[String] = {
choice match {
case 1 => listOne
case 2 => listTwo
}
}
}
def iTop(is : List[Imperative], choice : Int) = {
is.map{iMiddle(_, choice)}
}
def iMiddle(i : Imperative, choice : Int) = {
iBottom(i, choice)
}
def iBottom(i : Imperative, choice : Int) = {
i.activeList(choice)
}
val ps = List(new Imperative, new Imperative)
println(iTop(ps, 1)) //Prints "foo, bar" "foo,bar"
println(iTop(ps, 2)) //Prints "bat, baz" "bat, baz"
在面向对象的范式中,我可以使用内部状态来避免向下传递上下文:
class ObjectOriented extends Imperative {
var variable = listOne
}
def oTop(ps : List[ObjectOriented], choice : Int) = {
ps.map{ p => p.variable = p.activeList(choice) }
oMiddle(ps)
}
def oMiddle(ps : List[ObjectOriented]) = oBottom(ps)
def oBottom(ps : List[ObjectOriented]) = {
ps.map(_.variable) //No explicitly-passed-down choice, but hidden state
}
val oops = List(new ObjectOriented, new ObjectOriented)
println(oTop(oops, 1))
println(oTop(oops, 2))
在函数式语言中实现类似结果的惯用方法是什么?
也就是说,我希望下面的输出与上面的输出相似。
class Functional extends Object with ListHolder{
//IDIOMATIC FUNCTIONAL CODE
}
def fTop(fs : List[Functional], choice : Int) = {
//CODE NEEDED HERE TO CHOOSE LIST
fMiddle(fs)
}
def fMiddle(fs : List[Functional]) = {
//NO CHANGES ALLOWED
fBottom(fs)
}
def fBottom(fs : List[Functional]) = {
fs.map(_.activeList) //or similarly simple
}
def fs = List(new Functional, new Functional)
println(fTop(fs, 1))
println(fTop(fs, 2))
更新: 这会被认为是正常运行的吗?
class Functional extends Imperative with ListHolder{}
class FunctionalWithList(val activeList : List[String]) extends Functional{}
def fTop(fs : List[Functional], band : Int) = {
fMiddle(fs.map(f => new FunctionalWithList(f.activeList(band))))
}
def fMiddle(fs : List[FunctionalWithList]) = {
//NO CHANGES ALLOWED
fBottom(fs)
}
def fBottom(fs : List[FunctionalWithList]) = {
fs.map(_.activeList)
}
def fs = List(new Functional, new Functional)
println(fTop(fs, 1))
println(fTop(fs, 2))
【问题讨论】:
-
小记:不用写
extends Object with ListHolder。只需写extends ListHolder(类可以扩展特征)。
标签: scala functional-programming design-patterns idioms