I have a function with function type :
newtonRootSequence' :: Double -> Double -> [Double]
and function definition:
newtonRootSequence' xn d = [(xn + (d * (1/xn))) div 2] ++ newtonRootSequence' ((xn + (d * (1/xn))) div 2) d
upon receiving two values xn and d it should calculate the results for the given function
[(xn + (d * (1/xn))) div 2]
But for some reason on launch the compilator is not accepting the function with an error:
Couldnt match expected type '(Integer->Integer->Integer->) ->Integer ->Double with actual type double the function (xn + (d * (1/xn))) div 2) is applied to two arguments
This error occurs to the part where I try to send the result of the equation into the recursive step
++ newtonRootSequence' ((xn + (d * (1/xn))) div 2) d
As already mentioned in the comments:
div
as an infix function, you have to enclose it in backticks div
is for integral division with truncation towards negative infinity, not for dividing Double
These two points are the cause for your error message.
To divide Doubles
, use the /
operator like you already did in your expression 1/xn
.
With this your code should work. For clarity it could be transformed:
Extract the duplicated expression to compute the next xn
in the sequence into a where
clause. The expression can also be slightly simplified. Adding a single element in front of a list can simply be done with the cons operator (:)
:
newtonRootSequence' xn d = xn' : newtonRootSequence' xn' d where xn' = (xn + (d / xn)) / 2
You could use iterate :: (a -> a) -> a -> [a]
from the Prelude to separate the computation for a single step from the generation of the list of intermediate steps (note the flipped arguments):
sequenceStep :: Double -> Double -> Double sequenceStep s xn = (xn + (s / xn)) / 2 newtonRootSequence' :: Double -> Double -> [Double] newtonRootSequence' s x0 = iterate (sequenceStep s) x0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.