Haskell cannot match type

I'm still new to Haskell, and I have this piece of code, but ghc does not compile and does not give me an error.

This is the code:

data QT a = C a | Q (QT a) (QT a) (QT a) (QT a) deriving (Show)

moltiply :: QT a -> Int -> QT a
moltiply (C a) x = (C (a * x))
moltiply (Q a b c d) x = Q (moltiply a x) (moltiply b x) (moltiply c x) (moltiply d x)

And this is the error I get:

Couldn't match expected type ā€˜a’ with actual type ā€˜Int’
      ā€˜a’ is a rigid type variable bound by
          the type signature for multiply :: QT a -> Int -> QT a
          at file.hs:12:15
    Relevant bindings include
      a :: a (bound at file.hs:13:15)
      multiply :: QT a -> Int -> QT a
        (bound at file.hs:13:1)
    In the second argument of ā€˜(*)’, namely ā€˜x’
    In the first argument of ā€˜C’, namely ā€˜(a * x)’
+4
source share
2 answers

When you write

moltiply :: QT a -> Int -> QT a

you tell GHC that this function will work with any type ainside your type QT, but then you write

moltiply (C a) x = (C (a * x))

and try to multiply the value a, which can be of any type c Int. Does this seem to be wrong?

You can fix this in two ways:

  • Ask GHCi which is the most common type moltiplyby deleting the type signature and uploading the file to GHCi:

    Ī»> :t moltiply
    moltiply :: Num a => QT a -> a -> QT a
    

    ( ) .

  • Int, , moltiply QT Int:

    moltiply :: QT Int -> Int -> QT Int
    
+8

, Int *, - Int.

moltiply :: QT Int -> Int -> QT Int

moltiply :: Num a => QT a -> a -> QT a

-

moltiply :: (Num a, Integral b) => QT a -> b -> QT a
moltiply (C a) x = (C (a * fromIntegral x))
moltiply (Q a b c d) x = Q (moltiply a x) (moltiply b x) (moltiply c x) (moltiply d x)
+2

Source: https://habr.com/ru/post/1617784/


All Articles