user2878641
user2878641

Reputation:

Working with IO Monad in Haskell

If i have two constants:

type A = Int  
type B = Int  

and then apply the function:

Number :: String −> (Int −> Bool) −> IO Int
Number n = do
    num <- fmap getNumber getLine
    if num >0 || num <= A || num <= B then num else putStrln "Invalid Number!"

is this correct ?

Upvotes: 0

Views: 182

Answers (1)

wit
wit

Reputation: 1622

First line num <- fmap getNumber getLine is correct (if getNumber = read), but second line is not

if num >0 || num <= A || num <= B then num else putStrln "Invalid Number!"

Let's look at second part of if expression:

num :: Int, but putStrln "Invalid Number!" :: IO ()

But they MUST have the same type!

If we rewrite then return num, these means type return num :: IO Int, but still putStrln "Invalid Number!" :: IO ()

First part of if it is not correct at all: A and B are types, not data constructors

we could write (num > (x :: A) ), this means same as num > (x :: Int), like these:

num > 0 || num <= (3 :: A) || num <= (42 :: B)

Updated

Sure, name of function couldn't be Number with capital letter. All function are start with lowercase letter.

P.S. n in your example is an unused variable

Valid functions looks like:

numA = 3
numB = 42

number = do
    num <- fmap read getLine
    if num > 0 || num <= numA || num <= numB 
      then return (Just num)
      else putStrln "Invalid Number!" >> return Nothing

Upvotes: 1

Related Questions