Why will `read "1" :: Maybe Int` type check? - haskell

I wonder why read "1" :: Maybe Int will type check and throw an exception in runtime.
Is it possible that read can ever return a Maybe a? That is what Text.Read.readMaybe is supposed to do.
Prelude> read "1" :: Maybe Int
*** Exception: Prelude.read: no parse

I wonder why read "1" :: Maybe Int would type check
Because "1" has the type String and is thus acceptable as an argument to read and Maybe Int implements Read and is thus acceptable as a return type of Read.
and throw an exception in runtime.
Because "1" is not a valid string representation of a Maybe Int.
Is it possible that read can ever return a Maybe a?
Yes, for example read "Just 42" :: Maybe Int is Just 42 and read "Nothing" :: Maybe Int is Nothing.
Basically any string that you might get out of show x where x :: Maybe Int can also be fed as an argument to read to get a Maybe Int.
Or more generally, any output of show x where x :: T and T is an instance of Show and Read, can probably be fed to read to get back a value of type T - though of course instances can be defined arbitrarily, so not every type that implements Read and Show necessarily adheres to that "contract".

In short: you parse the textual representation of the Maybe a type, not a as a non-total function where Nothing is used to specify a parse failure.
Well read is usually the opposite of show. It will thus parse a representation of an object, that is frequently how you would write the object as a cascade of data constructors into an object.
Now Maybe a is a type of the Show family, given the elements it wraps are an instance of Show as well, something like:
instance Show a => Show (Maybe a) where
show Nothing = "Nothing"
show (Just x) = "Just "++ show x
(In reality it is a bit more complex, since it will also introduce brackets in case you wrap a Just 1 in a Just for example).
So the opposite can be parsed as well. For example:
Prelude> read "Nothing" :: Maybe Int
Nothing
Prelude> read "Just 5" :: Maybe Int
Just 5
So a Maybe a as a type of read is not meant for a "non-total" function, but to parse the textual representation of a Maybe a type.
So it parses strings with a prefix "Nothing" and "Just" (and also can parse some such "expressions" with brackets).

Related

Is any Atom data type in Haskell?

When I read/show String I get/expect the result to be quoted. If I want to omit quotes, I can implement some type like:
newtype Atom = Atom String deriving (Eq, Ord)
instance Read Atom where ...
instance Show Atom where ...
But my question is: does such type already exist somewhere in libraries, in the base, may be? I just found some Data.Atom but seems it something different (XML, etc).
No. If you find yourself wanting this, it means you're using Show in an unintended way. The idea of show is that is should always yield valid Haskell code. The Show String instance guarantees this, by safely quoting and escaping the contents. Short of that, you would of course in general not get Haskell code. Now, sure there are applications where you want to display something and don't care about whether it's Haskell code, but that shouldn't be show then.
Usually, if you have a string anyway, you should just use putStrLn directly.
Since Read and Show are for converting data to/from strings, you can just use the id function :)
But seriously, a String is already the output of its own read or show, if you don't want it quoted.
Say, for example, to print any other value (or a String, if you want it to appear quoted), you do:
putStrLn (show "Hello") -- prints "Hello", with quotes.
whereas, to print a string unquoted, you can simply do:
putStrLn "Hello" -- prints Hello, unquoted.
Because of this, I don't think there is any utility for this (it is trivial, after all); in fact, your Atom instances would simply be:
instance Read Atom where read = Atom
instance Show Atom where show (Atom s) = s
Depending on what you're doing, you may want to inspect the type and use print for non-strings and putStrLn for strings like this:
import Data.Typeable
printAny :: (Show a, Typeable a) => a -> IO ()
printAny a = case cast a of
Just str -> putStrLn str
Nothing -> print a
Then, as desired:
*Main> printAny "no quotes"
no quotes
*Main> printAny (10 :: Int)
10

Pass no char to a function that is expecting it in Haskell

I am working with Haskell and I have defined the following type
--Build type Transition--
data Transition = Transition {
start_state :: Int,
symbol :: Char,
end_state :: Int
} deriving Show
and I would like to be able to define the following Transition
Transition 0 '' 1
which would be mean "a transition given by no symbol" (I need it to compute the epsilon closure of a NFA). How can I do this?
Thank you!
Well the idea of defining a type is that every value you pass to that field is a "member" of that type. Char only contains only characters (and the empty string is not a character) and undefined (but it is advisable not to use undefined here).
Usually in case you want to make values optional, you can use a Maybe a type instead, so:
data Transaction = Transaction {
start_state :: Int,
symbol :: Maybe Char,
end_state :: Int
} deriving Show
So now we can pass two kinds of values: Nothing which thus should be interpreted as "no character", or Just x, with x a character, and this thus acts as a character, so in your case, that would be:
Transaction 0 Nothing 1
Maybe is also an instance of Functor, Applicative and Monad, which should make working with Maybe types quite convenient (yes it can sometimes introduce some extra work, but by using fmap, etc. the amount of pattern matching shifting to Maybe Char should be rather low).
Note: like #amalloy says, an NFA (and DFA) has Transitions, not Transactions.

Understanding readMaybe (Text.Read)

I'm currenlty learning Haskell and have questions regarding this example found in Joachim Breitner's online course CIS194:
import Text.Read
main = putStrLn "Hello World. Please enter a number:" >>
getLine >>= \s ->
case readMaybe s of -- why not `readMaybe s :: Maybe Int` ?!
Just n -> let m = n + 1 in
putStrLn (show m)
Nothing -> putStrLn "That’s not a number! Try again"
The code does exactly what expected, that is it returns an integer +1 if the input is an integer and it returns "That’s not a number! Try again" otherwise (e.g. if the input is a Double).
I don't understand why readMaybe s only returns Just n if n is of type Int. The type of readMaybe is readMaybe :: Read a => String -> Maybe a and therefore I thought it would only work if the line read instead:
case readMaybe s :: Maybe Int of
In fact if I just prompt > readMaybe "3" in ghci, it returns Nothing, whereas > readMaybe "3" :: Maybe Int returns Just 3.
To sum up, my question is the following: how does the compiler now that s is parsed to an Int and not something else (e.g. Double) without the use of :: Maybe Int? Why does it not return Nothing everytime ?
I hope my question was clear enough, thanks a lot for your help.
TL;DR: The context of readMaybe s tells us that it's a Num a => Maybe a, defaulting makes it a Maybe Integer.
We have to look at all places where the result of readMaybe is used to determine its type.
We have
Nothing, which doesn't tell us aynthing about a
Just n, and n is used in the context m = n + 1.
Since m = n + 1, we now know that n's type must be an instance of Num, since (+) :: Num a => a -> a -> a and 1 :: Num a => a. At this point the type isn't clear, therefore it gets defaulted:
4.3.4 Ambiguous Types, and Defaults for Overloaded Numeric Operations
topdecl -> default (type1 , ... , typen) (n>=0)
A problem inherent with Haskell -style overloading is the possibility of an ambiguous type. For example, using the read and show functions defined in Chapter 10, and supposing that just Int and Bool are members of Read and Show, then the expression
let x = read "..." in show x -- invalid
is ambiguous, because the types for show and read,
show :: forall a. Show a =>a ->String
read :: forall a. Read a =>String ->a
could be satisfied by instantiating a as either Int in both cases, or Bool. Such expressions are considered ill-typed, a static error.
We say that an expression e has an ambiguous type if, in its type forall u. cx =>t, there is a type variable u in u that occurs in cx but not in t. Such types are invalid.
The defaults defined in the Haskell report are default (Integer, Double), e.g. GHC tries Integer first, and if that doesn't work it tries to use Double.
Since Integer is a valid type in the context m = n + 1, we have m :: Integer, therefore n :: Integer, and at last readMaybe s :: Maybe Integer.
If you want to disable defaults, use default () and you'll be greeted by ambiguous types errors, just as you expected.
There indeed some underlying magic, due to how type inference works.
Here's a simpler example, run inside GHCi:
> print (1 :: Integer)
1
> print (1 :: Float)
1.0
Prelude> print 1
1
In the last line, 1 is a polymorphic value of type Num a => a, i.e. a value inside any numeric type like Integer and Float. If we consider that value inside type Integer, we print it as "1". If we consider it as a Float, we print it as "1.0". Other numeric types may even have different print formats.
Still, GHCi in the last line decides that 1 is an Integer. Why?
Well, it turns out that the code is ambiguous: after all 1 could be printed in different ways! Haskell in such cases raises an error, due to the ambiguity. However, it makes an exception for numeric types (those inc lass Num), to be more convenient to program. Concretely, when a numeric type is not precisely determined by the code, Haskell uses its defaulting rules, which specify which numeric types should be used.
GHC can warn when defaulting happens, if wanted.
Further, the types are propagated. If we evaluate
case readMaybe s of
Just x -> let z = x + length ['a','z']
in ...
GHC knows that length returns an Int. Also, (+) operates only on arguments of the same type, hence x has to be an Int as well. This in turns implies that the call readMaybe s has to return Maybe Int. Hence, the right Read instance for Ints is chosen.
Note how this information is propagated backwards by the type inference engine, so that the programmer does not have to add type annotations which can be deduced from the rest of the code. It happens very frequently in Haskell.
One can always be explicit, as in
readMaybe s :: Maybe Int
-- or, with extensions on, one can mention the variable part of the type, only
readMaybe s # Int
If you prefer, feel free to add such annotations. Sometimes, they make the code more readable since they document your intent. Whoever reads the code, can immediately spot which Read instance is being used here without looking at the context.

General function for reading numbers in Haskell

So, I wanted to get a Float from user and I have made this function :
getFloat :: IO Float
getFloat = do
string <- getLine
return (read string :: Float)
Now I would like to know how to make a more general function that can return ints, doubles and floats all in one go.
I have tried using Num type class to accomodate more possibilities but it doesn't work.
This is as far as I have got, it compiles but I'm not sure what I'm doing here exactly nor if it works at all.
etNumber :: (Read a) => IO a
getNumber = do
string <- getLine
return (read string)
When you write the signature
getNumber' :: Num a => IO a
it means this action will need to be able to offer any result type a that the caller might request – provided the type is an instance of the Num class. So essentially, the action knows nothing about the type it has to produce, though it can use the methods of that particular Num instance:
class Num a where
fromInteger :: Integer -> a
(+) :: a -> a -> a
...
Note that this does not give you any tools to generate fractional/floating-pt. numbers, only integer ones. You could in fact write
getNumber' :: Num a => IO a
getNumber' = do
i <- readLn
return $ fromInteger i
but this is pretty useless, indeed it'll fail if you actually attempt to read something like 0.3 to a float – because that can't be pulled through the intermediate Integer type.
You could do this:
getNumber'' :: Fractional a => IO a
getNumber'' = do
q <- readLn
return $ fromRational q
in this case, the input will first be read as an arbitrary-precision rational type (which can deal with decimal-fraction input) and then converted to the desired final type, like Double1. However, this can not be an integer type, because those obviously could not handle the possible fractional inputs!
Maybe what you envision is this:
getNumber''' :: IO (∃a. Num a => a)
which would be an existential type. That's basically a constrained dynamic type, i.e. the type is not chosen at compile-type by inference from what the caller wants, but instead at runtime, choosing a suitable type that can properly deal with the particular string input (integer if possible, floating if needed).
Well, Haskell doesn't have2 existential types, and for good reasons. Its standard parametric polymorphism is rather more useful because you actually get guarantees that some type will be exactly what you specify at compile time. Value should be integral? Make it an Integer; if then a decimal-fraction turns up in the input you get a meaningful error message right a way. Value might be fractional? Make it Rational or Double; these of course include integral values as well.
At any rate, there's no real reason to constrain the action to any numerical class. If you make it polymorphic at all, you should constrain it only as much as needed for the implementation (i.e., Read). To sum up: simply use readLn, don't write any getTʏᴘᴇ action at all.
1As a general rule, never use Float except when you're sure Double is not what you want.
2Well, it has a (generally disrecommended) workaround: existentially qualified record constructors.
{-# LANGUAGE GADTs #-}
data SomeNum where
SomeNum :: Num a => a -> SomeNum
getNumber'''' :: IO SomeNum

Converting IO Int to Int

I've created a combobox from converting a xmlWidget to a comboBox with the function castTocomboBox and now I want to get the text or the index of the active item. The problem is that if I use the comboBoxGetActive function it returns an IO Int result and I need to know how can I obtain the Int value. I tried to read about monads so I could understand what one could do in a situation like this but I don't seem to understand. I appreciate all the help I can get. I should probably mention that I use Glade and gtk2hs.
As a general rule you write something like this:
do
x <- somethingThatReturnsIO
somethingElseThatReturnsIO $ pureFunction x
There is no way to get the "Int" out of an "IO Int", except to do something else in the IO Monad.
In monad terms, the above code desugars into
somethingThatReturnsIO >>= (\x -> somethingElseThatReturnsIO $ pureFunction x)
The ">>=" operator (pronounced "bind") does the magic of converting the "IO Int" into an "Int", but it refuses to give that Int straight to you. It will only pass that value into another function as an argument, and that function must return another value in "IO". Meditate on the type of bind for the IO monad for a few minutes, and you may be enlightened:
>>= :: IO a -> (a -> IO b) -> IO b
The first argument is your initial "IO Int" value that "comboBoxGetActive" is returning. The second is a function that takes the Int value and turns it into some other IO value. Thus you can process the Int, but the results of doing so never escape from the IO monad.
(Of course there is the infamous "unsafePerformIO", but at your level of knowledge you may be certain that if you use it then you are doing it wrong.)
(Actually the desugaring is rather more complicated to allow for failed pattern matches. But you can pretend what I wrote is true)
Well, there is unsafePerformIO: http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/System-IO-Unsafe.html#v:unsafePerformIO
(If you want to know how to find this method: Go to http://www.haskell.org/hoogle and search for the signature you need, here IO a -> a)
That said, you probably heard of "What happens in IO stays in IO". And there are very good reasons for this (just read the documentation of unsafePerformIO). So you very likely have a design problem, but in order to get help from experienced Haskellers (I'm certainly not), you need to describe your problem more detailed.
To understand what those types are –step by step–, first look up what Maybe and List are:
data Maybe a = Nothing | Just a
data [a] = [] | a : [a]
(Maybe a) is a different type than (a), like (Maybe Int) differs from (Int).
Example values of the type (Maybe Int) are
Just 5 and Nothing.
A List of (a)s can be written as ([ ] a) and as ([a]). Example values of ([Int]) are [1,7,42] and [ ].
Now, an (IO a) is a different thing than (a), too: It is an Input/Output-computation that calculates a value of type (a). In other words: it is a script or program, which has to be executed to generate a value of type (a).
An Example of (IO String) is getLine, which reads a line of text from standard-input.
Now, the type of comboBoxGetActive is:
comboBoxGetActive :: ComboBoxClass self => self -> IO Int
That means, that comboBoxGetActive is a function (->) that maps from any type that has an instance of the type-class ComboBoxClass (primitive type-classes are somehow similar to java-interfaces) to an (IO Int). Each time, this function (->) is evaluated with the same input value of this type (self) (whatever that type is), it results in the same value: It is always the same value of type (IO Int), that means that it is always the same script. But when you execute that same script at different times, it could produce different values of type (Int).
The main function of your program has the type (IO ()), that means that the compiler and the runtime system evaluate the equations that you program in this functional language to the value of main, which will be executed as soon as you start the program.

Resources