Search code examples
haskelltypesfunctional-programminglazy-evaluationpurely-functional

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. My [lambda] function is this:

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?


Solution

  • You need to match on r e.g.

    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