Home > Mobile >  Haskell - Couldn't match expected type `(a2, a6)' with actual type `Pos'
Haskell - Couldn't match expected type `(a2, a6)' with actual type `Pos'

Time:11-30

In my code i have a data type Pos:

data Pos = Pos { col :: Char, row :: Int } deriving Show

and I have a function where I get 2 Pos instances and just want to return a string which describes a certain case:

whichCase :: Pos -> Pos -> String
whichCase start finish
    | snd start == snd finish = "horizontal"
    | fst start == fst finish = "vertical"
    | otherwise = "diagonal"

I get this Proble here:

 * Couldn't match expected type `(a2, a6)' with actual type `Pos'
    * In the first argument of `snd', namely `x'
      In the first argument of `(==)', namely `snd x'
      In the expression: snd x == snd y
    |
147 |     | snd x == snd y = "horizontal"
    |           ^

From what I understood from the Error message it says it expected x to be somthing different than Pos ? What did I do wrong ?

CodePudding user response:

fst and snd have the purpose of extracting values from a tuple.

ghci> fst (37, "flub")
37
ghci> snd (True, -3.14)
-3.14

Now, your Pos type certainly is tuple-like (it is isomorphic to (Char,Int)), but that doesn't mean it is a tuple type. It's a record type instead, which means you can use the record field labels to do much the same thing:

ghci> col (Pos 'n' 5)
'n'
ghci> row (Pos 'n' 5)
5

So, you also should use those in your code.

  • Related