Haskell报错Could not match expected type with actual type排查
代码错误原因
你的代码updateSystem函数存在两处类型不匹配问题:
- 递归调用时参数括号错误:你写的
updateSystem time System(xs)会被Haskell解析为传入3个参数(time、System构造函数本身、列表xs),但updateSystem定义只接收Double和System两个参数,正确的参数写法应该是updateSystem time (System xs),把System xs整体作为第二个参数传入。 - 列表拼接操作类型不匹配:
moveBody time x返回的是Body类型,而updateSystem的返回值是System类型,二者无法直接用列表连接符(:)拼接。你需要先取出递归返回的System中存储的Body列表,完成拼接后再重新包装为System类型。
修正方案
你可以直接通过模式匹配取出System中的列表,使用map批量处理所有Body,写法更简洁也不会出错:
updateSystem :: Double -> System -> System updateSystem time (System bodies) = System (map (moveBody time) bodies)
如果你要保留原来的递归写法,可修改为如下形式:
updateSystem :: Double -> System -> System updateSystem time (System []) = System [] updateSystem time (System (x:xs)) = System (moveBody time x : rest) where System rest = updateSystem time (System xs)
内容的提问来源于stack exchange,提问作者Grigorii Kostarev
相关产品推荐
相关产品推荐

