2

我有以下数据可以有或没有船:

data LaserCollisionResult = NoCollision | LaserToLaserCollision Ship | LaserToShipCollision Ship deriving (Eq, Show)

然后,稍后,我尝试检查 LaserCollisionResult 是否属于 LaserToLaserCollision 类型,但出现错误。我的 lambda 函数是这样的:

laserPaths' = map (\(p,r) -> if r == LaserToLaserCollision then doSomethingWith p else p) $ zip laserPaths laserCollisionResults

我得到的错误是:

Couldn't match type 'LaserCollisionResult' with 'Ship -> LaserCollisionResult'
Expected type: [Ship -> LaserCollisionResult]
Actual type: [LaserCollisionResult]
In the second argument of 'zip', namely laserCollisionResults.

如何检查laserCollisionResults 中的LaserCollisionResult 是否属于LaserToLaserCollision 类型?

4

2 回答 2

5

将您的 lambda 替换为

(\(p,r) -> case r of {LaserToLaserCollision _ -> doSomethingWith p; _ -> p})

顺便说一句,为此您不需要派生Eq实例。

于 2015-02-14T10:15:52.437 回答
2

你需要匹配r例如

laserPaths' = map (\(p,r) -> if isLaserCollision r then doSomethingWith p else p) $ zip laserPaths laserCollisionResults
  where isLaserCollision (LaserToLaserCollision _) = True
        isLaserCollision _ = False

或者你可以匹配内联:

 laserPaths' = map (\(p, r) -> case r of { (LaserToLaserCollision _) -> doSomethingWith p ; _ -> p}) $ zip laserPaths laserCollisionResults
于 2015-02-14T10:14:57.027 回答