基本Haskell IO(IO字符串 - > Int)?

时间:2015-04-28 00:46:46

标签: haskell

初学者哈斯克勒在这里。我试图用一个简单的命令行程序代表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."

1 个答案:

答案 0 :(得分:4)

使用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."