Haskell IO与数字

Rom*_*kov 1 io haskell

任何人都可以帮忙解决这个问题吗?

编写一个程序,询问用户直角三角形的底边和高度,计算其面积并将其打印到屏幕上.交互应该类似于:

The base?
3.3
The height?
5.4
The area of that triangle is 8.91
Run Code Online (Sandbox Code Playgroud)

解决:

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
Run Code Online (Sandbox Code Playgroud)

eph*_*ent 13

你有什么工作,但是将纯粹与IO分开是更好的Haskell风格.你的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)
Run Code Online (Sandbox Code Playgroud)

Applicative实际上并不是必需的,它只是提供了一些漂亮的中缀运算符.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)
Run Code Online (Sandbox Code Playgroud)

在这样的短节目,它并不真正的事情那么多,但是请注意,即使是那些进口的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)
Run Code Online (Sandbox Code Playgroud)