gpt4 book ai didi

functional-programming - Elm 中的类型错误

转载 作者:行者123 更新时间:2023-12-02 04:45:50 28 4
gpt4 key购买 nike

我是 Elm 的新手,但不是函数式编程的新手,所以这个错误既令人沮丧又令人尴尬。我写了一个 50 行的 elm 程序,但我遇到了这些难以捉摸的类型错误。简而言之,有人能找到这段代码中的类型错误吗!!!
您可以将此代码直接粘贴到在线 elm editor .

import Mouse
import Window

--Model
type Tracker = {x:Int, y:Int, th:Float}
tracker:Tracker
tracker = {x=100, y=100, th=0.0}
trkS:Signal Tracker
trkS = constant tracker

dir: Tracker -> (Int, Int) -> (Int,Int) -> Float
dir t (x',y') (w',h') =
let (x,y) = toFloatT (x',y')
(w,h) = toFloatT (w',h')
(dx, dy) = (x - w/2, h/2 - y)
in (atan2 (dy - (toFloat t.y)) (dx - (toFloat t.x)))

dirS:Signal Float
dirS = lift3 dir trkS Mouse.position Window.dimensions

changeV: Float -> Tracker -> Tracker
changeV theta t =
{t | th <- theta }

moveTracker: Int -> Tracker -> Tracker
moveTracker time' t =
let time = toFloat time'
x' = (toFloat t.x) + 3 * time *(cos t.th)
y' = (toFloat t.y) + 3 * time *(sin t.th)
in {t | x <- round x'
, y <- round y'}

step:(Int, Float) -> Tracker -> Tracker
step (dt, dir) = moveTracker dt . changeV dir

render (w',h') trk =
let (w,h) = (toFloat w', toFloat h')
in collage w' h'
[ngon 3 20 |> filled green
|> move (trk.x, trk.y)
, asText (trk.th) |> toForm]

input:Signal (Int,Float)
input =
let delta = lift (round . (\t -> t/20)) (fps 25)
in sampleOn delta (lift2 (,) delta dirS)

main =
lift2 render Window.dimensions (foldp step tracker input)

--Helper functions
toFloatT (x,y) = (toFloat x, toFloat y)
roundF = toFloat . round

最佳答案

实际和预期的顺序

我将您的代码放入在线编辑器中,它给了我很多预期/实际是 Int/Float 错误。我认为这是可以改进的地方,但那是针对邮件列表的。
您应该知道,编译器告诉您的预期/实际类型有时可以颠倒,至少对于某些人的直觉而言是这样。

调试问题

为了调试这个问题,我首先阅读并尝试理解您的代码。代码很简单,但程序的目标对我来说并不是很清楚。无论如何,我没有发现任何不寻常的地方。我特别关注编译器指出类型错误所在的 main 代码行,但这似乎不是问题的根源。

添加类型注释

所以我继续为还没有的函数添加类型注释。通常,当您添加更多类型注释时,编译器可以为您提供更好的定位。
我补充说:

render: (Int,Int) -> Tracker -> Element

main : Signal Element

toFloatT: (Int,Int) -> (Float,Float)

roundF: Float -> Float

问题

然后编译器告诉我错误出在渲染函数中。在那里我注意到你制作了窗口尺寸的浮点值并且没有使用它们,然后使用了整数 xyTrackermove 中的元组中.这就是错误所在,因为 move采用浮点元组。

解决方案

因此,当您使用以下改编的渲染函数时,编译:

render: (Int,Int) -> Tracker -> Element
render (w',h') trk =
let trkPos = toFloatT (trk.x, trk.y)
in collage w' h'
[ngon 3 20 |> filled green
|> move trkPos
, asText (trk.th) |> toForm]

我希望通过向您展示我调试此类型错误的方法,您下次可以更轻松地找到解决方案。

长话短说

问题是 render功能:你给move函数 Int 的元组s 代替 Float 的元组它期望。修复和编译代码可以找到here .

关于functional-programming - Elm 中的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19802016/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com