[英]Ask user for list input in Haskell
I found this code online, but it's not running.我在网上找到了这段代码,但它没有运行。
main = do
xs <- getLine []
print xs
So how do I ask the user for list input in Haskell?那么如何在 Haskell 中向用户询问列表输入呢? I am new to Haskell, please explain when you answer.
我是 Haskell 的新手,请在回答时解释。 Thanks.
谢谢。
You do it eg like this:你这样做,例如像这样:
main :: IO ()
main = do
xs <- getLine
let { ints :: [Int]
; ints = read xs
}
print $ take 2 ints
and you must type in the input in a valid list syntax, eg并且您必须以有效的列表语法输入输入,例如
[1,2,3]
Do take note, each line in a do
-block must start at the same indentation level (unless explicit separators { ; }
are used).请注意,
do
-block 中的每一行都必须以相同的缩进级别开始(除非使用了显式分隔符{ ; }
)。
getLine
is an IO
action that produces a string, nothing else. getLine
是一个IO
操作,它产生一个字符串,没有别的。 You need to process that string once you receive it.收到该字符串后,您需要对其进行处理。 As an example, here's an
IO
action that will parse an appropriate input into a list of Int
values.例如,这是一个
IO
操作,它将适当的输入解析为Int
值列表。
getIntList :: IO [Int]
getIntList = fmap read getLine
main = do
ints <- getIntList
print ints
There is a Read
instance for lists, so the following works:列表有一个
Read
实例,因此以下工作:
> read "[1,2,3]" :: [Int]
[1,2,3]
getIntList
uses the Functor
instance for IO
to apply read
to the string that getLine
will produce; getIntList
使用IO
的Functor
实例将read
应用于getLine
将产生的字符串; read
's concrete type will be inferred from the type given to getIntList
: since getIntList :: IO [Int]
, then fmap read :: IO String -> IO [Int]
, and so read :: String -> [Int]
will be used. read
的具体类型将从提供给getIntList
的类型推断:因为getIntList :: IO [Int]
,然后fmap read :: IO String -> IO [Int]
,因此read :: String -> [Int]
将使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.