두 개의 목록이있는 특성이 있다고 가정 해보십시오. 가끔은 그 중 하나에, 때로는 다른 사람들에게도 관심이 있습니다.상태 선택 컨텍스트를 호출 스택에 전달하는 것을 피하는 "기능적 방법"은 무엇입니까?
trait ListHolder {
val listOne = List("foo", "bar")
val listTwo = List("bat", "baz")
}
나는 내가 목록 사이에서 선택을해야하는 상황이있는 상단에, 함수 호출의 체인을 가지고 있지만, 하단에있는 나는 특성을 사용합니다. 명령형 패러다임
, I는 기능을 통해 컨텍스트를 건네 객체 지향 패러다임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"
는 I 컨텍스트를 전달 피하기 위해 내부 상태를 사용할 수
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))
작은 메모 : 'ListHolder와 함께 extends 객체'를 쓸 필요가 없습니다. 'extends ListHolder'라고 써라. (클래스는 특성을 확장 할 수있다.) – Jesper