[英]How to check type in haskell
I don't know how to check type of variable in haskell, Here i mean , when i read something from console with getLine
,however i expect it to be an interger but user can enter a string also,then i don't want my program to crash. 我不知道怎么检查haskell中的变量类型,我的意思是,当我用
getLine
从控制台读取内容时,但我希望它是一个整数但用户也可以输入一个字符串,然后我不想要我程序崩溃。 For example if someone inputs a string and i try to convert it to Int
then it will crash(exception) so i want to check whether it is convertable or not. 例如,如果有人输入一个字符串,我尝试将其转换为
Int
然后它将崩溃(异常)所以我想检查它是否可转换。 How do i do that ? 我怎么做 ? Thanks for any help :)
谢谢你的帮助 :)
main1 = do
let g <- getLine
k = g :: Int
if(k :: Int)
then ........
EDIT: Notice you always have a string from getLine
- that's the type it returns. 编辑:请注意,你总是有一个来自
getLine
的字符串 - 这是它返回的类型。 If that string contains an ascii representation of a number then great and keep reading. 如果该字符串包含数字的ascii表示,那么很好并继续阅读。
If you have a string, g
, and say g :: Int
the compiler will simply so "no, you are wrong, that's a String". 如果你有一个字符串
g
,并且说g :: Int
那么编译器就会这样“不,你错了,那是一个字符串”。 You need to perform a translation - parse the string and compute an Int. 您需要执行转换 - 解析字符串并计算Int。 The most readily available methods are
read
in the Prelude and readMaybe
in Text.Read
. 最容易获得的方法在Prelude中
read
, readMaybe
在Text.Read
中Text.Read
。
Read will work but throws exceptions on invalid input: Read会起作用但会抛出无效输入的异常:
Prelude> read "4742" :: Int
4742
Prelude> read "no" :: Int
*** Exception: Prelude.read: no parse
Prelude> read "191andmore"
*** Exception: Prelude.read: no parse
The maybe variant is exception safe: 也许变体是异常安全的:
Prelude> import Text.Read
Prelude Text.Read> readMaybe "181" :: Maybe Int
Just 181
Prelude Text.Read> readMaybe "no" :: Maybe Int
Nothing
Prelude Text.Read> readMaybe "211andmore" :: Maybe Int
Nothing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.