我目前正在处理这个Haskell问题,而且我似乎陷入困境。
写一个函数evalpoly,它将询问用户单个变量多项式的次数,然后读入多项式的系数(从最高功率到最低),然后读取一个值,并输出值在该值处评估的多项式。举个例子:
> evalpoly
What is the degree of the polynomial: 3
What is the x^3 coefficient: 1.0
What is the x^2 coefficient: - 2.0
What is the x^1 coefficient: 0
What is the x^0 coefficient: 10.0
What value do you want to evaluate at: -1.0
The value of the polynomial is 7.0
截至目前,我有这个:
evalpoly :: IO ()
evalpoly = putStr "What is the degree of the polynomial: " >>
getLine >>= \xs ->
putStr "What is the x^" >>
putStr (show xs) >>
putStr " coefficient: " >>
putStrLn ""
我如何添加循环和计算?
答案 0 :(得分:4)
我完全破坏了这一点,所以随时都可以随意停下来试着继续自己
不是将其全部推入这个单一的功能,而是将其分解为更小的任务/功能。
让我们从这开始。
显而易见的是要求一个值 - 如果我们在上面,我们可以确保用户输入是好的(我正在使用Text.Read.readMaybe
:
query :: Read a => String -> IO a
query prompt = do
putStr $ prompt ++ ": "
val <- readMaybe <$> getLine
case val of
Nothing -> do
putStrLn "Sorry that's a wrong value - please reenter"
query prompt
Just v -> return v
请注意,我已经添加了": "
部分,因此您无需为prompt
向您的用户提出所有问题变得几乎无足轻重:
queryDegree :: IO Int
queryDegree = query "What is the degree of the polynomial"
queryCoef :: Int -> IO (Int, Double)
queryCoef i = do
c <- query prompt
return (i,c)
where prompt = "What is the x^" ++ show i ++ " coefficient"
queryPoint :: IO Double
queryPoint = query "What value do you want to evaluate at"
请注意,我提供的功能与系数一起 - 这使得计算更容易一些但在这里我并不是绝对必要的(你可能会认为这不仅仅是函数在此时应该做的,后来使用{ {1}}也获得权力)
一旦你看到mapM
以及它能做什么,现在要求所有的输入都非常容易 - 这就是你通常希望写一个循环的地方:
zip
评估这个我只需要评估给定点的每个术语(即列表中的每个 power,系数对) - 您可以使用queryPoly :: IO [(Int, Double)]
queryPoly = do
n <- queryDegree
mapM queryCoef [n,n-1..0]
- 我们之后只需要总结一下(map
可以做到这一点):
sum
相当无聊:
evaluate :: Double -> [(Int, Double)] -> Double
evaluate x = sum . map (\ (i,c) -> c*x^i)
我只需要询问输入,评估值然后呈现它:
presentResult :: Double -> IO ()
presentResult v = putStrLn $ "The vaule of the polynomial is " ++ show v
这是一个运行示例
evalpoly :: IO ()
evalpoly = do
p <- queryPoly
x <- queryPoint
presentResult $ evaluate x p
请注意,我喜欢进入无缓冲,因为如果我没有它,我偶尔会在Windows上遇到麻烦 - 你可能没有
What is the degree of the polynomial: 3
What is the x^3 coefficient: 1.0
What is the x^2 coefficient: -2.0
What is the x^1 coefficient: Hallo
Sorry that's a wrong value - please reenter
What is the x^1 coefficient: 0
What is the x^0 coefficient: 10.0
What value do you want to evaluate at: -1.0
The vaule of the polynomial is 7.0