gpt4 book ai didi

scala - 奇怪的 Scala 错误

转载 作者:行者123 更新时间:2023-12-04 23:32:34 24 4
gpt4 key购买 nike

我尝试创建抽象的回合制游戏和抽象的 AI:

abstract class AGame {
type Player
type Move // Player inside

def actPlayer : Player
def moves (player : Player) : Iterator[Move]
def play (move : Move)
def undo ()
def isFinished : Boolean
def result (player : Player) : Double
}

abstract class Ai[Game <: AGame] {
def genMove (player : Game#Player) : Game#Move
}

class DummyGame extends AGame {
type Player = Unit
type Move = Unit

def moves (player : Player) = new Iterator[Move] {
def hasNext = false
def next = throw new Exception ("asd")
}

def actPlayer = ()

def play (move : Move) {
}

def undo () {
}

def isFinished = true

def result (player : Player) = 0
}

class DummyAi[Game <: AGame] (game : Game) extends Ai[Game] {
override def genMove (player : Game#Player) : Game#Move = {
game.moves (player).next
}
}

我想我必须使用这种奇怪的类型访问器,比如 Game#Player。
我得到了非常令人费解的错误。我想了解一下:
[error] /home/lew/Devel/CGSearch/src/main/scala/Main.scala:41: type mismatch;
[error] found : Game#Player
[error] required: DummyAi.this.game.Player
[error] game.moves (player).next
[error] ^

最佳答案

def moves (player : Player)意味着 moves为此接受一名球员 Game .
Game#Player是任何玩家的类型 Game .所以moves (player)是类型不匹配。

这是一个简单的例子,说明为什么它一定是不匹配的。假设它不是,看看接下来会发生什么:

class Game2 extends DummyGame {
override type Player = Boolean
override type Move = Boolean

override def moves(player : Boolean) = new Iterator[Boolean] {...}
}

val game2: DummyGame = new Game2
// game2.Player is Boolean

val dummyGameAi = new DummyAi[DummyGame](game2)
// DummyGame#Player == Unit, so the type of genMove for Ai[DummyGame] is
// def genMove (player : Unit) : Unit

dummyGameAi.genMove(())
// this calls game2.moves(()), which doesn't typecheck

为了让它工作,我们可以改变 genMove 的类型.如果我们将游戏作为参数传递(无论如何它都有意义),我们可以使用依赖于路径的类型:
abstract class Ai[Game <: AGame] {
def genMove (game : Game)(player : game.Player) : game.Move
// now game.moves (player) typechecks
}

关于scala - 奇怪的 Scala 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3033164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com