你有什么作品,但它是更好的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