初学者Haskeller在这里。我试图用一个简单的命令行程序来表示pizza equation,该程序需要很多人并返回适当数量的披萨来点餐。我知道我需要将输入(IO String
)转换为Int,然后使用show
将结果转换为字符串。我如何IO String -> Int
?还是我给这只猫剥皮都错了?
import System.Environment
import System.IO
pizzas :: Integral a => a -> a
pizzas x = div (x * 3) 8
main = do
putStrLn "How many people are you going to feed?"
arg <- getLine
-- arg needs to IO String -> Int
-- apply pizzas function
-- Int -> String
putStrLn "You will need to order " ++ string ++ " pizzas."
最佳答案
如果可能,使用read会将类型从字符串转换为适当的类型
并使用show将整数转换为其字符串表示形式
arg <- getLine
let num = pizzas (read arg)
putStrLn $ "You will need to order " ++ (show num) ++ " pizzas."
或执行以下操作:
arg <- readLn :: IO Int
let num = pizzas arg
putStrLn $ "You will need to order " ++ (show num) ++ " pizzas."