Lar*_*ien 11 design-patterns functional-programming scala idioms
说我有一个有两个列表的特征.有时候我对这个有兴趣,有时候会对此感兴趣.
trait ListHolder {
val listOne = List("foo", "bar")
val listTwo = List("bat", "baz")
}
Run Code Online (Sandbox Code Playgroud)
我有一系列函数调用,在其中我有我需要在列表之间选择的上下文,但在其底部我使用了特征.
在命令式范例中,我通过函数传递上下文:
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"
Run Code Online (Sandbox Code Playgroud)
在面向对象的范例中,我可以使用内部状态来避免传递上下文:
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))
Run Code Online (Sandbox Code Playgroud)
在功能语言中实现类似结果的惯用方法是什么?
也就是说,我希望以下输出类似于上面的输出.
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))
Run Code Online (Sandbox Code Playgroud)
更新:这会被认为是正常的功能吗?
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))
Run Code Online (Sandbox Code Playgroud)
好吧,人们总是可以使用monad和monadic comprehension来处理这类事情,但问题的核心在于,不是将选项传递到堆栈中,而是将函数返回堆栈,直到有人知道如何解决问题可以处理它.
def fTop(fs : List[Functional]) = {
fMiddle(fs)
}
def fMiddle(fs : List[Functional]) = {
fBottom(fs)
}
def fBottom(fs : List[Functional]) = {
(choice: Int) => fs map (_ activeList choice)
}
Run Code Online (Sandbox Code Playgroud)
然后
println(fTop(fs)(1))
Run Code Online (Sandbox Code Playgroud)
一旦你开始为这种事物开发模式,你最终会得到各种各样的monad(每种monad代表一种特定的模式).