Understanding readMaybe (Text.Read)

I am studying Haskell and have questions regarding this example found in the Joachim Breitner CIS194 online course :

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 is expected, that is, returns an integer of +1 if the input is an integer, and it returns โ€œThats not number! Try againโ€ otherwise (for example, if the input is Double). I do not understand why it readMaybe sreturns only Just nif it nhas a type Int. The type readMaybeis equal readMaybe :: Read a => String -> Maybe a, so I thought it would work only if the string would look like this:

case readMaybe s :: Maybe Int of

In fact, if I just invite > readMaybe "3"to ghci, it returns Nothing, while it > readMaybe "3" :: Maybe Intreturns Just 3.

, : s Int, - (, Double) :: Maybe Int? Nothing ?

, , .

+4
2

TL; DR: readMaybe s , Num a => Maybe a, Maybe Integer.


, readMaybe .

  • Nothing, a
  • Just n, n m = n + 1.

m = n + 1, , n Num, (+) :: Num a => a -> a -> a 1 :: Num a => a. , default ed:

4.3.4

topdecl   ->  default (type1 , ... , typen)   (n>=0)

, Haskell-style, - . , , 10, , Int Bool Read Show,

let x = read "..." in show x -- invalid

, ,

show  :: forall a. Show a =>a ->String
read  :: forall a. Read a =>String ->a

a Int , Bool. , .

, e , u. cx = > t, u u, cx, t. .

default, Haskell, default (Integer, Double), . GHC Integer, , Double.

Integer m = n + 1, m :: Integer, n :: Integer , , readMaybe s :: Maybe Integer.

default s, default (), , .

+5

- - , .

: GHCi:

> print (1 :: Integer)
1
> print (1 :: Float)
1.0
Prelude> print 1
1

1 Num a => a, , Integer Float. Integer, "1". Float, "1.0". . โ€‹โ€‹

, GHCi , 1 Integer. ?

, , : 1 -! - . , (, Num), . , , Haskell , , .

GHC , , .

, .

case readMaybe s of
  Just x -> let z = x + length ['a','z']
            in ...

GHC , length Int. , (+) , x Int. , readMaybe s Maybe Int. , Read Int.

, , , . Haskell.

,

readMaybe s :: Maybe Int
-- or, with extensions on, one can mention the variable part of the type, only
readMaybe s @ Int

, . , . , , , Read , .

+1

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


All Articles