你有什麼作品,但它是更好的Haskell風格從IO分離純。您的getTriArea
計算不需要鎖定在IO monad中:將其解除!
import Control.Applicative
prompt :: (Read a) => String -> IO a
prompt s = putStr s >> read <$> getLine
triArea :: (Fractional a) => a -> a -> a
triArea base height = (base * height)/2
main :: IO()
main = do
area <- triArea <$> prompt "The base? " <*> prompt "The height? "
putStrLn $ "The area of that triangle is " ++ show (area :: Float)
應用並非實際必要,它只是提供了一些漂亮的中綴操作符。 Monad工作得很好。
import Control.Monad
prompt :: (Read a) => String -> IO a
prompt s = putStr s >> fmap read getLine
triArea :: (Fractional a) => a -> a -> a
triArea base height = (base * height)/2
main :: IO()
main = do -- pick one of the following two lines
area <- liftM2 triArea (prompt "The base? ") (prompt "The height? ")
area <- return triArea `ap` prompt "The base? " `ap` prompt "The height? "
putStrLn $ "The area of that triangle is " ++ show (area :: Float)
在這樣一個簡短的程序,它並沒有真正無論所有的東西,但要注意,即使是那些進口,triArea
定義可以保持純潔。
prompt :: (Read a) => String -> IO a
prompt s = putStr s >> getLine >>= return . read
triArea :: (Fractional a) => a -> a -> a
triArea base height = (base * height)/2
main :: IO()
main = do
base <- prompt "The base? "
height <- prompt "The height? "
let area = triArea base height
putStrLn $ "The area of that triangle is " ++ show (area :: Float)
你到目前爲止嘗試了什麼? – 2009-12-08 18:40:42
Haskell IO帶有浮點數和數字已經破壞了我的想法,但我已經得到了答案。 所以我想現在解決了 – 2009-12-08 19:18:51
然後點擊其中一個答案旁邊的複選標記。 – 2009-12-09 00:20:32