I'm trying to implement 4th order Runge-Kutta in Haskell, but I find it difficult to use the Haskell type system for this task. Can someone help? I wish to change the 'State' and 'DState' types into typeclasses in the following code:
data State = State Double deriving (Show)
data DState = DState Double deriving (Show)
update :: State -> DState -> State
update (State x) (DState y) = State (x+y)
add :: DState -> DState -> DState
add (DState x) (DState y) = DState (x + y)
scale :: Double -> DState -> DState
scale h (DState x) = DState (h*x)
update_rk4 :: State -> (Double -> State -> DState) -> Double -> Double -> State
update_rk4 y f t h = update y (scale (h*(1.0/6.0)) s) where
s = add k1 (add s2 (add s3 k4))
s2 = scale 2 k2
s3 = scale 2 k3
k1 = f t y
k2 = f (t+0.5*h) ( update y (scale (0.5*h) k1) )
k3 = f (t+0.5*h) ( update y (scale (0.5*h) k2) )
k4 = f (t+h) ( update y (scale h k3) )
It seems difficult to formulate the type classes since State and DState are intertwined in the sense that specific instance of State requires a specific instance of DState.. Or is there possibly some other approach that I fail to see?