首页 > 解决方案 > 无法将预期类型与 Haskell 中的实际类型匹配

问题描述

我编写了以下代码:

type Mass = Double
type Position = (Double, Double)
type Velocity = (Double, Double)

data Body = Body Mass Position Velocity
data System = System [Body]

renderBody :: Body -> Picture
renderBody (Body mass (x, y) velocity) = object
  where 
    object = translated x y (solidCircle mass)

renderSystem :: System -> Picture
renderSystem (System []) = blank
renderSystem (System (x:xs)) = renderBody(x)<>renderSystem(System(xs))

moveBody :: Double -> Body -> Body
moveBody time (Body mass (x, y) (vx, vy)) = new_body
  where
    new_x = x + vx * time
    new_y = y + vy * time
    new_body = (Body mass (new_x, new_y) (vx, vy))

updateSystem :: Double -> System -> System
updateSystem time (System []) = (System [])
updateSystem time (System(x:xs)) = moveBody time x : updateSystem time System(xs)

我无法理解以下错误

有什么问题?

提前致谢。

标签: haskell

解决方案


您没有申请updateSystem timetype 的值System;您将其应用于数据构造函数SystemBody值列表xs。您需要调整括号以创建必要的 type 值System

updateSystem time (System(x:xs)) = moveBody time x : updateSystem time (System xs)

updateSystem但是,您可以通过使用mapSystem换行的列表来简化定义。

updateSystem :: Double -> System -> System
updateSystem time (System xs) = System (map (moveBody time) xs)

提取 type 的值[Body],对其进行映射moveBody time以获取Body's 的新列表,并将列表重新包装为新System值。


推荐阅读