开发者

scala: what is the inner class method for dynamic scoping?

i'm trying to evaluate all 3 methods of dynamic scoping described here (https://wiki.scala-lang.org/display/SYGN/Dynamic-scope) and i understand all but the "inner class method". it is described as follows:

It is possible to achieve a similar effect to dynamic scoping using nested class definitions. By defining the entire state-consuming code as inner classes of a state object, and instantiating that object each time a new global state is required, all the contained code gets direct access to the state variables via the parent reference.

To avoid defining the entire program in a single file, this approach for most purposes mandates the use of component mixins in order to compose the program into a single class.

I don't quite understand this - is it possible for someone to give some example code showing this? The second approach of implicit parameters makes sense to me, but the article also suggests that it can be combined with 开发者_高级运维the inner class method and I don't quite see that either. Thanks!


Like this:

case class Board(rows: Int, columns: Int) {
    case class Pos(row: Int, column: Int) {
        require(0 <= row && row < rows && 0 <= column && column < columns)

        def neighbors = for {
            nRow <- Set(row - 1, row, row + 1)
            if 0 <= nRow && nRow < rows
            nColumn <- Set(column - 1, column, column + 1)
            if 0 <= nColumn && nColumn < columns
            if (nRow, nColumn) != (row, column)
        } yield Pos(nRow, nColumn)
    }
}

Here, Pos refers to a "context" that is on Board: rows and columns. For example:

scala> val board = Board(5, 5)
board: Board = Board(5,5)

scala> val pos = board.Pos(0, 0)
pos: board.Pos = Pos(0,0)

scala> println(pos.neighbors)
Set(Pos(0,1), Pos(1,0), Pos(1,1))

Changes in one Board as seen by the Pos associated with that instance, but not with others:

scala> val board2 = Board(2, 2)
board2: Board = Board(2,2)

scala> println(board.Pos(1,1).neighbors+"\n"+board2.Pos(1, 1).neighbors)
Set(Pos(1,0), Pos(1,2), Pos(2,0), Pos(2,1), Pos(0,0), Pos(2,2), Pos(0,1), Pos(0,2))
Set(Pos(0,0), Pos(0,1), Pos(1,0))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜