Haskell: Couldn't match expected type ‘(a, b0)’ with actual type ‘(a, b, h)’

1381 views haskell
5

My code:

g :: (a, b, h) -> (c, d, i) -> ((a, c))
g x y = ((fst x, fst y))

Why does it print the following errors?:

ax.hs:11:15: error:
    • Couldn't match expected type ‘(a, b0)’
                  with actual type ‘(a, b, h)’
    • In the first argument of ‘fst’, namely ‘x’
      In the expression: fst x
      In the expression: ((fst x, fst y))
    • Relevant bindings include
        x :: (a, b, h) (bound at ax.hs:11:3)
        g :: (a, b, h) -> (c, d, i) -> (a, c) (bound at ax.hs:11:1)
   |
11 | g x y = ((fst x, fst y))
   |               ^

ax.hs:11:22: error:
    • Couldn't match expected type ‘(c, b1)’
                  with actual type ‘(c, d, i)’
    • In the first argument of ‘fst’, namely ‘y’
      In the expression: fst y
      In the expression: ((fst x, fst y))
    • Relevant bindings include
        y :: (c, d, i) (bound at ax.hs:11:5)
        g :: (a, b, h) -> (c, d, i) -> (a, c) (bound at ax.hs:11:1)
   |
11 | g x y = ((fst x, fst y))

Please help. I'm not sure why this is happening. How do I fix it? Thank you

answered question

fst :: (a,b) -> a. You need something like an fst3, which would work on triples, but that's not in the Prelude. Pretty easy to write yourself, though.

so fst works with only two element tuples?

fst only applies to pairs (2-tuples)

1 Answer

11

fst :: (a, b) -> a only works for 2-tuples, not tuples with a different arity than 2.

You can use pattern matching to obtain the first item of the 3-tuple, and personally I would use pattern matching for the second tuple as well, since this is - in my opinion - a more transparent syntax:

g :: (a, b, h) -> (c, d, i) -> (a, c)
g (x, _, _) (y, _, _) = (x, y)

Note that ((a, c)) is the same as (a, c), so we can remove the extra parenthesis.

posted this

Have an answer?

JD

Please login first before posting an answer.