2009-12-08 68 views
1

任何人都可以帮助这个exersise?Haskell IO与数字

写一个程序,询问用于右 成角度三角形的底边和高度的用户 ,计算出其面积 和它打印在屏幕上。该 交互看起来应该像 :

The base? 
3.3 
The height? 
5.4 
The area of that triangle is 8.91 

与解决:

getTriArea :: IO Float 
getTriArea = do 
putStr "The base? " 
base <- getLine 
putStr "The height? " 
height <- getLine 
let ar = ((read base :: Float) * (read height :: Float))/ 2 
return ar 

main = do 
result <- getTriArea 
putStr $ "The area of that triangle is " ++ show result 
+4

你到目前为止尝试了什么? – 2009-12-08 18:40:42

+0

Haskell IO带有浮点数和数字已经破坏了我的想法,但我已经得到了答案。 所以我想现在解决了 – 2009-12-08 19:18:51

+0

然后点击其中一个答案旁边的复选标记。 – 2009-12-09 00:20:32

回答

13

你有什么作品,但它是更好的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) 
1
getTriArea :: IO Float 
getTriArea = do 
putStr "The base? " 
base <- getLine 
putStr "The height? " 
height <- getLine 
let ar = ((read base :: Float) * (read height :: Float))/ 2 
return ar 

main = do 
result <- getTriArea 
putStr $ "The area of that triangle is " ++ show result 
+1

这些读取的类型注释和参数是多余的。你可以写'读取基地*读取高度/ 2'。函数应用程序是左关联的。 – Chuck 2009-12-08 19:40:46

0

(B H)/ 2 = B(H/2)=(B/2)ħ= B H/2在数学,它们都是相同的,并且给出相同的结果。所以更好地写简单的基地*高度/ 2