-2

I have a function(eval) to evaluate polynomial.

eval coeffs value = .......

coeffs is list of coefficents.

value is for x in math

Ex) to calculate 3x^2 + 2x + 1 with x=20

coeffs is stored reverse order.

when I type coefficient like above, it is stored like this [1,2,3]

program working like this and last part is wrong (the value of the polynomial): here is my code

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

how can I evaluate the polynomial with coefficient and x value?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
kim
  • 27
  • 2
  • 1
    Your question could use a bit of work, it looks like your formatting is off and your wording isn't very clear. Do you already have a function `eval`, or are you tasked to write one? – bheklilr Apr 21 '16 at 18:58
  • 1
    well I guess it's your homework/exercise so you should start by telling us what you tried - do you even have the representation set up? Show us some code :D – Random Dev Apr 21 '16 at 18:58
  • possible duplicate of https://stackoverflow.com/questions/36438057/i-o-loop-in-haskell/36441613#36441613 (**caution** the link will spoil the complete homework) – Random Dev Apr 21 '16 at 19:01
  • how can i make eval function with list of coefficient and value? – kim Apr 21 '16 at 19:08
  • 1
    What is the definition of `polyEvaluate`? – David Young Apr 21 '16 at 20:15

1 Answers1

3

some hints...

you can write a series of powers easily

powers n = iterate (*n) 1

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

and combine this with your coefficients

> zip [1,2,3] $ powers 20 
[(1,1),(2,20),(3,400)]

you have to think what to do to change this to a sum of product of the pairs (use zipWith)

karakfa
  • 66,216
  • 7
  • 41
  • 56