Haskell:if-then-else使用非对称构造函数块和数据

Haskell:if-then-else使用非对称构造函数块和数据,haskell,types,functional-programming,lazy-evaluation,purely-functional,Haskell,Types,Functional Programming,Lazy Evaluation,Purely Functional,我有以下数据,可以有船也可以没有船: data LaserCollisionResult = NoCollision | LaserToLaserCollision Ship | LaserToShipCollision Ship deriving (Eq, Show) 然后,稍后,我尝试检查LaserCollisionResult是否为LaserToLaserCollision类型,但我得到一个错误。我的[lambda]函数是: laserPaths' = map (\(p,r) ->

我有以下数据,可以有船也可以没有船:

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
实例。

map f$zip xs ys
zipWith(curry f)xs ys
相同。您可以将
laserPaths'
简化为
zipWith(\p r->case r of{…})laserPaths laserCollisionResults
@Cirdec谢谢您的帮助。