[英]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 ? 这个对吗 ?
First line num <- fmap getNumber getLine
is correct (if getNumber = read
), but second line is not 第一行
num <- fmap getNumber getLine
是正确的(如果getNumber = read
),但是第二行不是
if num >0 || num <= A || num <= B then num else putStrln "Invalid Number!"
Let's look at second part of if
expression: 让我们看一下
if
表达式的第二部分:
num :: Int
, but putStrln "Invalid Number!" :: IO ()
num :: Int
,但是putStrln "Invalid Number!" :: IO ()
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 ()
如果我们重写
then return num
,则意味着键入return num :: IO Int
,但仍然putStrln "Invalid Number!" :: IO ()
putStrln "Invalid Number!" :: IO ()
First part of if
it is not correct at all: A
and B
are types, not data constructors if
它根本不正确的第一部分: A
和B
是类型,而不是数据构造函数
we could write ( num > (x :: A)
), this means same as num > (x :: Int)
, like these: 我们可以编写(
num > (x :: A)
),这意味着与num > (x :: Int)
,如下所示:
num > 0 || num <= (3 :: A) || num <= (42 :: B)
Updated 更新
Sure, name of function couldn't be Number
with capital letter. 当然,函数名不能
Number
以大写字母。 All function are start with lowercase letter. 所有功能均以小写字母开头。
PS n
in your example is an unused variable 您的示例中的PS
n
是未使用的变量
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.