2009-12-08 111 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