如何在Haskell中读取/添加/打印数字字符串 [英] How to read/ add/ print a number string in Haskell

查看:61
本文介绍了如何在Haskell中读取/添加/打印数字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果下面是我的代码,请在下面.我希望能够接受如下所示的用户输入:"6 1 2 3 4 5 6",然后获取总和并打印出来.了解如何使用输入的第一个数字作为总数也很酷.因此,这里的第一个数字是6,输入的总数是6.

Below if my code right now. I want to be able to take in user input like the following: "6 1 2 3 4 5 6" and the get the sum and print. it would also be cool to understand how to use the first number entered as the total numbers. SO here the first number is 6 and the total numbers inputted is 6.

在此先感谢您为我提供帮助.我已经研究了数周,无法弄清楚.

Thank you in advance for helping me with this. I have been researching for weeks and cannot figure this out.

main = do
    putStrLn "Enter how many numbers:" -- clearer
    num<-getLine
    putStrLn("Enter a number: ")
    numberString <- getLine 
    let numberInt =(read numberString :: Int)
    print (numberInt*4)
    main

推荐答案

似乎您需要一个辅助递归函数来读取 num 个整数,或者需要一些帮助程序,例如 replicateM ,这使得编写代码更加容易.

It seems you either need an auxiliary recursive function for reading num integers, or some helper like replicateM, which makes writing the code a little easier.

replicateM num action 准确地 num 次运行 action 次,并将所有操作结果收集在一个列表中.

replicateM num action runs action exactly num times, and collects all the action results in a list.

main = do
    putStrLn "Enter how many numbers:" -- clearer
    num<-getLine
    numbers <- replicateM num $ do
       putStrLn("Enter a number: ")
       numberString <- getLine
       return (read numberString :: Int)
    -- here we have numbers :: [Int]
    ...

然后您可以从那里继续.

You can then continue from there.

如果您想使用辅助功能,则可以编写

If instead you want to use an auxiliary function, you can write

readInts :: Int -> IO [Int]
readInts 0 = return []
readInts n = do
    putStrLn("Enter a number: ")
    numberString <- getLine
    otherNumbers <- readInts (n-1)   -- read the rest
    return (read numberString : otherNumbers)


最后,我们可以直接使用结合了两者的 readLn ,而不是先使用 getLine 然后再使用 read .


Finally, instead of using getLine and then read, we could directly use readLn which combines both.

这篇关于如何在Haskell中读取/添加/打印数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆