Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell-读入用户输入的数字字符串并添加它们_Haskell - Fatal编程技术网

Haskell-读入用户输入的数字字符串并添加它们

Haskell-读入用户输入的数字字符串并添加它们,haskell,Haskell,我早些时候问了一个问题,剩下的问题比答案多 我希望能够做到以下几点:在数字列表后面的列表中输入整数的数量 示例 4 1 2 3 4 或 现在我有下面的代码不起作用 import Control.Monad readLn = do putStrLn "Enter how many numbers:" -- clearer num<-getLine numbers<- replicateM num action putStrLn("Enter a n

我早些时候问了一个问题,剩下的问题比答案多

我希望能够做到以下几点:在数字列表后面的列表中输入整数的数量

示例

4 1 2 3 4

现在我有下面的代码不起作用

import Control.Monad


readLn = do
    putStrLn "Enter how many numbers:" -- clearer
    num<-getLine
    numbers<- replicateM num action
    putStrLn("Enter a number: ")
    numberString <- getLine
    return (read numberString :: Int)
    -- here we have numbers :: [Int]
import-Control.Monad
readLn=do
putStrLn“输入多少数字:”--更清晰

num如果您想要一行输入,它不需要包含数字的数量,因为您只需在空白处拆分该行即可获得列表

foo :: IO [Int]
foo = do
   putStr "Enter your numbers, separated by whitespace (e.g. 4 5 3 2): "
   line <- getLine
   return $ map read (words line)
readLn
相当于
fmap read getLine
;您将获得一行输入,对结果字符串调用
read

replicItem
将嵌套的
do
块定义的
IO
操作作为其第二个参数。您正在传递一个未定义的变量
action
。该操作生成一个
IO Int
值,该值
replicItem
重复
n
次,并将结果
IO Int
值组合成一个
IO[Int]
值。(这是
replicateM
replicate
之间的区别,这将产生一个操作列表,
[IO Int]



因为
foo
foo'
都被声明为具有类型
IO[Int]
,编译器可以推断出使用
read
readLn

的正确特定类型,而@Rainbacon是OP前面的问题,可能是重复的。@chepner是的,这是完全相同的问题。如果OP不理解他们在另一个问题上得到的答案,他们应该对收到的答案进行评论,要求澄清,而不是提出新的问题
foo :: IO [Int]
foo = do
   putStr "Enter your numbers, separated by whitespace (e.g. 4 5 3 2): "
   line <- getLine
   return $ map read (words line)
-- No error handling or line editing, for simplicity
foo' :: IO [Int]
foo' = do
    putStr "How many numbers?: "
    n <- readLn
    replicateM n $ do
      putStr "Enter a number: "
      readLn