我正在尝试在 Haskell 中实现 4 阶 Runge-Kutta,但我发现很难将 Haskell 类型系统用于此任务。有人可以帮忙吗?我希望在以下代码中将“State”和“DState”类型更改为类型类:
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) )
似乎很难制定类型类,因为 State 和 DState 在某种意义上是交织在一起的,即 State 的特定实例需要 DState 的特定实例。或者是否有其他我看不到的方法?