Haskell read function with no annotation - haskell

Does haskell read function implicitly converts a data type into another?
import IO
main = do
putStrLn "Enter an interger: "
num <- getLine
putStr "Value + 3 is "
putStrLn (show((read num) + 3))
So, haskell interpreter automatically changes num's data type from string to int to handle '+ 3'?

read has type Read a => String -> a, which means that it can convert a String into any type that is an instance of the Read type class. Which type it will use depends on the surrounding code. In this case you write read num + 3. The + operator is also overloaded to work for any type that is an instance of Num, so the type of read num + 3 is (Read a, Num a) => a. Haskell has a mechanism that chooses a default type whenever the Num type class remains in the final type of an expression. In this case it defaults to Integer, so the final type is Integer.
You can see this in action by enabling the -Wtype-defaults warning which is also included in -Wall:
Test.hs:5:15: warning: [-Wtype-defaults]
• Defaulting the following constraints to type ‘Integer’
(Show a0) arising from a use of ‘show’ at Test.hs:5:15-34
(Num a0) arising from a use of ‘+’ at Test.hs:5:20-33
(Read a0) arising from a use of ‘read’ at Test.hs:5:21-28
• In the first argument of ‘putStrLn’, namely
‘(show ((read num) + 3))’
In a stmt of a 'do' block: putStrLn (show ((read num) + 3))
In the expression:
do putStrLn "Enter an interger: "
num <- getLine
putStr "Value + 3 is "
putStrLn (show ((read num) + 3))
|
5 | putStrLn (show((read num) + 3))
|

Here you are using
show :: Show a => a -> String
read :: Read a => String -> a
(+) :: Num a => a -> a -> a
3 :: Num a => a
on the same type a. So, Haskell searches for a type a satisfying Show a, Read a, Num a.
In principle, this would be rejected since the type is ambiguous, but Haskell mandates a special rules for Num, causing a to be defaulted, usually to Integer. Since that satisfies also Show and Read, the program type-checks.

Related

Haskell warning

I have written the code (I'm new to haskell, very new) and can't solve the warning.
problem:
funk :: Num a => a -> a
funk a = a + 10
main :: IO()
main = print (funk 10 )
Warning:
Warnings: 1
/home/anmnv/Desktop/qqq.hs: line 4, column 8:
Warning: • Defaulting the following constraints to type ‘Integer’
(Show a0) arising from a use of ‘print’ at qqq.hs:4:8-23
(Num a0) arising from a use of ‘funk’ at qqq.hs:4:15-21
• In the expression: print (funk 10)
In an equation for ‘main’: main = print (funk 10)
It simply says that you did not specify the type for 10. It can strictly speaking by any type that is an member of the Num typeclass, but the compiler uses defaulting rules, and thus picks an Integer.
You can give Haskell a type constraint to determine the type of 10, for example:
funk :: Num a => a -> a
funk = (+ 10)
main :: IO ()
main = print (funk (10 :: Integer))

Ambigous type variable that prevents the constraint

I am fiddling around with IO and i do not understand the following error :
* Ambiguous type variable `a0' arising from a use of `readLine'
prevents the constraint `(Console a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instance exist:
instance Console Int -- Defined at Tclass.hs:8:14
* In the second argument of `(+)', namely `readLine'
In the second argument of `($)', namely `(2 + readLine)'
In the expression: putStrLn . show $ (2 + readLine)
|
17 | useInt =putStrLn . show $ (2+readLine)
Code
module Tclass where
import System.Environment
class Console a where
writeLine::a->IO()
readLine::IO a
instance Console Int where
writeLine= putStrLn . show
readLine = do
a <- getLine
let b= (read a)::Int
return b
useInt::IO()
useInt =putStrLn . show $ (2+readLine)
P.S i do not understand shouldn't the compiler infer the type of the instance for readLine and make the addition with 2 in the useInt method ?
2 is not only an Int in Haskell but it is of any numeric type, including Float,Double,Integer,.... Its type is Num a => a -- a polymorphic type fitting each numeric type.
So, you could use (2::Int) instead. Then you'll discover that (2::Int) + readLine is a type error, since readLine :: Int is wrong, we only get readLine :: IO Int.
You can try this, instead
useInt :: IO ()
useInt = do
i <- readLine
putStrLn . show (2 + i :: Int)

Read list of unknown type from user input Haskell:

Say I have the following function:
readList :: IO [Int]
readList = do
putStrLn "Please enter the list as a string"
putStrLn "Example: input of '1 2 3 4 5' will map to [1,2,3,4,5]"
line <- getLine
return $ map read $ words line
printNaive :: [Int] -> IO ()
printNaive xs = putStrLn "The maximum surpasser count is:" >> putStrLn "0"
main :: IO ()
main = readList >>= printNaive
This function works as expected. Now lets say I was going to extend this code to be more generic, and read in a line of any type of thing as a list:
readList :: (Read a, Int a) -> IO [a]
readList = do
putStrLn "Please enter the list as a string"
putStrLn "Example: input of '1 2 3 4 5' will map to [1,2,3,4,5]"
line <- getLine
return $ map read $ words line
printNaive :: (Eq a) => [a] -> IO ()
printNaive xs = putStrLn "The maximum surpasser count is:" >> putStrLn "0"
main :: IO ()
main = readList >>= printNaive
This fails with:
Ambiguous type variable ‘a0’ arising from a use of ‘Lib.readList’
prevents the constraint ‘(Read a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Read Ordering -- Defined in ‘GHC.Read’
instance Read Integer -- Defined in ‘GHC.Read’
instance Read a => Read (Maybe a) -- Defined in ‘GHC.Read’
...plus 22 others
...plus four instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
How would I go about writing this code, given I really don't care what type of thing it is as long as it conforms to Eq.
Additionally, say I wanted to provide a facility to specify what type the list is going to contain. (through another getLine say).
How would I extract a type from getLine, and how would I then cast every element in the map read $ words line to that particular type.
What you did wrong is in this line:
readList :: (Read a, Int a) -> IO [a]
What you probably want to get at with (Read a, Int a) is a type class constranit for the type a, meaning you want it to be readable and you want it to be some sort of integer.
Firstly you wrote your constraint wrong. A typeclass constraint is given before a => not a ->. Secondly Int is not a type class. Maybe try using Integral?
So your type signature should look like this:
readList :: (Read a, Integral a) => IO [a]
EDIT: A caveat is, however, that the a in the type signature has to be decided at compile time. In the first example in your question it would work out because the type of printNaive fixes a to be Int. That is not generally the case, however.

Specify list type for input

I'm learning Haskell and I've decided to to the H-99 problem set. Naturally, I've become stuck on the first problem!
I have the following code:
module Main where
getLast [] = []
getLast x = x !! ((length x) - 1)
main = do
putStrLn "Enter a list:"
x <- readLn
print (getLast x)
Compiling this code gives the following error:
h-1.hs:8:14:
No instance for (Read a0) arising from a use of `readLn'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Read () -- Defined in `GHC.Read'
instance (Read a, Read b) => Read (a, b) -- Defined in `GHC.Read'
instance (Read a, Read b, Read c) => Read (a, b, c)
-- Defined in `GHC.Read'
...plus 25 others
In a stmt of a 'do' block: x <- readLn
In the expression:
do { putStrLn "Enter a list:";
x <- readLn;
print (getLast x) }
In an equation for `main':
main
= do { putStrLn "Enter a list:";
x <- readLn;
print (getLast x) }
h-1.hs:9:9:
No instance for (Show a0) arising from a use of `print'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Show Double -- Defined in `GHC.Float'
instance Show Float -- Defined in `GHC.Float'
instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus 26 others
In a stmt of a 'do' block: print (getLast x)
In the expression:
do { putStrLn "Enter a list:";
x <- readLn;
print (getLast x) }
In an equation for `main':
main
= do { putStrLn "Enter a list:";
x <- readLn;
print (getLast x) }
That's a large error, but it seems to me that Haskell isn't sure what the input type will be. That's fine, and completely understandable. However, as this is supposed to work on a list of generics, I'm not sure how to specify that type. I tried this:
x :: [a] <- readLn
...as [a] is the type that Haskell returns for an empty list (found with :t []). This won't compile either.
As I'm a beginner, I know there's a lot I'm missing, but in a basic sense - how can I satisfy Haskell's type system with input code? I'm a Haskell beginner looking for a beginner answer, if that's at all possible. (Also, note that I know there's a better way to do this problem (reverse, head) but this is the way I came up with first, and I'd like to see if I can make it work.)
You can't hope to write something like this which will detect the type of x at run time -- what kind of thing you're reading must be known at compile time. That's why #Sibi's answer uses [Int]. If it can't be deduced, you get a compile time error.
If you want a polymorphic read, you have to construct your own parser which lists the readable types.
maybeDo :: (Monad m) => Maybe a -> (a -> m b) -> m b
maybeDo f Nothing = return ()
maybeDo f (Just x) = f x
main = do
str <- getLine
maybeDo (maybeRead str :: Maybe Int) $ \i ->
putStrLn $ "Got an Int: " ++ show i
maybeDo (maybeRead str :: Maybe String) $ \s ->
putStrLn $ "Got a String: " ++ show s
There are lots of ways to factor out this repetition, but at some point you'll have to list all the types you'll accept.
(An easy way to see the problem is to define a new type MyInt which has the same Read instance as Int -- then how do we know whether read "42" should return an Int or a MyInt?)
This should work:
getLast :: Num a => [a] -> a
getLast [] = 0
getLast x = x !! ((length x) - 1)
main = do
putStrLn "Enter a list:"
x <- readLn :: IO [Int]
print (getLast x)
why return 0 for an empty list, instead of an empty list?
Because it won't typecheck. Because you are returning [] for empty list and for other cases you are returning the element inside the list i.e a. Now since a type is not equal to list, it won't typecheck. A better design would be to catch this type of situation using the Maybe datatype.
Also, because of returning 0, the above function will work only for List of types which have Num instances created for them. You can alleviate that problem using error function.
However, this should work for a generic list, not just a list of Ints
or Numbers, right?
Yes, it should work for a polymorphic list. And you can create a function like getLast which will work for all type of List. But when you want to get input from the user, it should know what type of input you are giving. Because the typechecker won't be able to know whether you meant it as List of Int or List of Double or so on.

Can Either be used for a kind of simple polymorphism?

I tried writing a simple function that takes an Either type (possibly parameterized by two different types) and does one thing if it gets Left and another thing if it gets Right. the following code,
someFunc :: (Show a, Show b) => Either a b -> IO ()
someFunc (Left x) = print $ "Left " ++ show x
someFunc (Right x) = print $ "Right " ++ show x
main = do
someFunc (Left "Test1")
someFunc (Right "Test2")
However, this gives,
Ambiguous type variable `b0' in the constraint:
(Show b0) arising from a use of `someFunc'
Probable fix: add a type signature that fixes these type variable(s)
In a stmt of a 'do' expression: someFunc (Left "Test1")
and
Ambiguous type variable `a0' in the constraint:
(Show a0) arising from a use of `someFunc'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: someFunc (Right "Test2")
If I understand correctly, when I call the function with Left x, it is complaining because it doesn't know the type of the Right x variant, and vice-versa. However, this branch of the function is not used. Is there a better way to do this?
You can make this work by explicitly specifying the other type:
main = do
someFunc (Left "Test1" :: Either String ())
someFunc (Right "Test2" :: Either () String)
but I agree with x13n that this probably isn't the best way to do whatever you're trying to do. Note that someFunc is functionally identical to
someFunc :: (Show a) => Bool -> a -> IO ()
someFunc False x = print $ "Left " ++ show x
someFunc True x = print $ "Right " ++ show x
because the only information you derive from the structure of the Either is whether it's a Left or Right. This version also doesn't require you to specify a placeholder type when you use it.
This is a good question, because it made me think about why Haskell behaves this way.
class PseudoArbitrary a where
arb :: a
instance PseudoArbitrary Int where
arb = 4
instance PseudoArbitrary Char where
arb = 'd'
instance PseudoArbitrary Bool where
arb = True
reallyDumbFunc :: (PseudoArbitrary a, PseudoArbitrary b) =>
Either a b -> Either a b
reallyDumbFunc (Left x) = Right arb
reallyDumbFunc (Right x) = Left arb
So check this out. I've made a typeclass PseudoArbitrary, where instances of the typeclass provide a (pseudo-)arbitrary element of their type. Now I have a reallyDumbFunction that takes an Either a b, where both a and b have PseudoArbitrary instances, and if a Left was put in, I produce a Right, with a (pseudo-)arbitrary value of type b in it, and vice versa. So now let's play in ghci:
ghci> reallyDumbFunc (Left 'z')
Ambiguous type variable blah blah blah
ghci> reallyDumbFunc (Left 'z' :: Either Char Char)
Right 'd'
ghci> reallyDumbFunc (Left 'z' :: Either Char Int)
Right 4
Whoa! Even though all I changed was the type of the input, it totally changed the type and value of the output! This is why Haskell cannot resolve the ambiguity by itself: because that would require analyzing your function in complicated ways to make sure you are not doing things like reallyDumbFunc.
Well, that depends heavily on what you are trying to do, doesn't it? As you already found out, in order to use Left constructor, you need to know the type it constructs. And full type requires information on both a and b.
Better way to achieve polymorphism in Haskell is to use type classes. You can easily provide different implementations of "methods" for different instances.
Good comparison of both object-orientation and type classes concepts can be found here.

Resources