Haskell:if-then-else 块和具有非对称构造函数的数据

Haskell: if-then-else blocks and data with asymmetrical constructors

我有以下数据可以有没有Ship:

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 类型?

您需要在 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

将您的 lambda 替换为

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

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