1

Super basic question - but I can't seem to get a clear answer. The below function won't compile:

randomfunc :: a -> a -> b
randomfunc e1 e2
   | e1 > 2 && e2 > 2       = "Both greater"
   | otherwise              = "Not both greater"

main = do
   let x = randomfunc 2 1
   putStrLn $ show x

I'm confused as to why this won't work. Both parameters are type 'a' (Ints) and the return parameter is type 'b' (String)?

Error:

"Couldn't match expected type ‘b’ with actual type ‘[Char]’"

2 Answers 2

7

Not quite. Your function signature indicates: for all types a and b, randomfunc will return something of type b if given two things of type a.

However, randomFunc returns a String ([Char]). And since you compare e1 with 2 each other, you cannot use all a's, only those that can be used with >:

(>) :: Ord a => a -> a -> Bool

Note that e1 > 2 also needs a way to create such an an a from 2:

(> 2) :: (Num a, Ord a) => a -> Bool

So either use a specific type, or make sure that you handle all those constraints correctly:

randomfunc :: Int -> Int -> String

randomFunc :: (Ord a, Num a) => a -> a -> String
Sign up to request clarification or add additional context in comments.

Comments

2

Both parameters are type 'a' (Ints) and the return parameter is type 'b' (String)?

In a Haskell type signature, when you write names that begin with a lowercase letter such as a, the compiler implicitly adds forall a. to the beginning of the type. So, this is what the compiler actually sees:

randomfunc :: forall a b. a -> a -> b

The type signature claims that your function will work for whatever ("for all") types a and b the caller throws at you. But this is not true for your function, since it only works on Int and String respectively.

You need to make your type more specific:

randomfunc :: Int -> Int -> String

On the other hand, perhaps you intended to ask the compiler to fill out a and b for you automatically, rather than to claim that it will work for all a and b. In that case, what you are really looking for is the PartialTypeSignatures feature:

{-# LANGUAGE PartialTypeSignatures #-}

randomfunc :: _a -> _a -> _b

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.