Jader Martins
Jader Martins

Reputation: 789

Casting [Int] to [Double] from input

I have a list of constants and degrees of a polynomial equation and want to return a list of this composition for a value be applied and then summed. But this list comes as Int and my function expects a list of double.

poly :: [Double] -> [Double] -> [Double -> Double]
poly a b =
  let f x y = (*x) . (**y)
        in uncurry f <$> zip a b

-- does not work
poly ([1,2,3]:: [Double]) ([1,2,3]:: [Double])

How to cast a list of int to list of double?

Upvotes: 1

Views: 1164

Answers (2)

Jader Martins
Jader Martins

Reputation: 789

With @4castle and Victoria Ruiz I came up with the following:

poly :: [Int] -> [Int] -> [Double -> Double]
poly = zipWith $ \x y -> (* (fromIntegral x)) . (** (fromIntegral y))

apply ::  Double -> [Double -> Double] -> Double
apply x b = sum $ ($x) <$> b
-- l=left limiting, r=right limiting, a=coeficients, b=degrees
solve :: Int -> Int -> [Int] -> [Int] -> [Double]
solve l r a b =
  let h        = 0.001
      linspace = [fromIntegral l,fromIntegral l+h..fromIntegral r]
      p = poly a b
      area = sum $ map ((*h) . (`apply` p)) linspace
      volume = h * (sum $ map ((*pi) . (**2) .(`apply` p)) linspace)
  in [area,volume]

I think Haskell compiler with his strong type inference has some peculiarities that can't be directly solved by type cast.

Upvotes: 0

Victoria Ruiz
Victoria Ruiz

Reputation: 5013

You can use fromIntegral, which will convert from any Integral type into any Numeric type (Int, Integer, Rational, and Double).

More here: https://wiki.haskell.org/Converting_numbers

Upvotes: 5

Related Questions