简体   繁体   English

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

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

I have the following data which can have a Ship or not: 我有以下数据可以发货或不发货:

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

then, later on, I am trying to check if a LaserCollisionResult is of type LaserToLaserCollision, but I get an error. 然后,稍后,我试图检查LaserCollisionResult是否为LaserToLaserCollision类型,但是我收到错误。 My [lambda] function is this: 我的lambda函数是这样的:

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

The error I am getting is: 我得到的错误是:

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

How can I check whether a LaserCollisionResult in laserCollisionResults is of type LaserToLaserCollision? 如何检查laserCollisionResults中的LaserCollisionResult是否为LaserToLaserCollision类型?

Replace your lambda by 替换你的lambda

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

By the way, for this you don't need to derive an Eq instance. 顺便说一句,为此您不需要派生Eq实例。

You need to match on r eg 你需要匹配r例如

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

or you can match inline: 或者你可以匹配内联:

 laserPaths' = map (\(p, r) -> case r of { (LaserToLaserCollision _) -> doSomethingWith p ; _ -> p}) $ zip laserPaths laserCollisionResults

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM