评估Haskell中的多项式

时间:2016-04-21 18:55:49

标签: haskell

我有一个函数(eval)来评估多项式。

eval coeffs value = .......

coeffs是系数列表。

value适用于数学中的 x

  

例)计算   3x ^ 2 + 2x + 1,x = 20

coeffs以反向顺序存储。

当我输入如上所示的系数时,它会像[1,2,3]

一样存储

程序像这样工作,最后一部分是错误的(多项式的值): 这是我的代码

getCoeff 0 ls = do  return ls

getCoeff n ls = do  putStr "What is the x^"
            putStr (show(n-1))
            putStr " coefficient: "
            v <- getLine
            w <- getCoeff (n-1) ((read v :: Float):ls)
            return w


evalpoly = do   putStr "What is the degree of polynomial: "
        v <- getLine    
        l <- (getCoeff ((read v :: Int)+1) [])
        putStr "What value do you want to evaluate at: "
        x <- getLine    
        putStr "The value of the polynomial is: "
        putStr (show (polyEvaluate (l) (read x :: Float)))
        putStr "\n"

eval [] x = 0.0
eval (l) x = 
What is the degree of polynomial: 2
What is the x^2 coefficient: 3
What is the x^1 coefficient: 2
What is the x^0 coefficient: 1
What value do you want to evaluate at: 20
The value of the polynomial is 1241.0

如何用系数和x值来评估多项式?

1 个答案:

答案 0 :(得分:3)

一些提示......

你可以轻松写出一系列权力

powers n = iterate (*n) 1

> take 10 $ powers 2
[1,2,4,8,16,32,64,128,256,512]

并将其与系数

结合起来
> zip [1,2,3] $ powers 20 
[(1,1),(2,20),(3,400)]

您必须考虑如何将其更改为对的乘积之和(使用zipWith)