将多个信号传递给 Signal.map 会引发类型不匹配错误

Pass multiple signals to Signal.map throws type-mismatch errors

我正在尝试使用 elm - 0.15 打印鼠标光标与 window 中心的距离。例如,将光标放在 window 中心必须打印 (0,0).

我的代码是,

import Graphics.Element exposing (show)
import Mouse
import Signal
import Window

relativeMouse : (Int, Int) -> (Int, Int)
relativeMouse (ox, oy) (x,y) = (x - ox, y - oy)

center: (Int, Int) -> (Int, Int)
center (w,h) = (w/2, h/2)

main = Signal.map show <| relativeMouse (Signal.map center Window.dimensions Mouse.position)

elm-make basics.elm 至少抛出 4 个单独的 type-mismatch errors

如何在 elm 0.15 中将多个信号(window.dimensionsMouse.position)传递给一个函数(例如,relativeMouse)?

评论是对您的修改:

import Graphics.Element exposing (show)
import Mouse
import Signal
import Window

-- change type signature to match implementation
relativeMouse : (Int, Int) -> (Int, Int) -> (Int, Int)
relativeMouse (ox, oy) (x,y) = (x - ox, y - oy)

-- use // for integer division
center: (Int, Int) -> (Int, Int)
center (w, h) = (w // 2, h // 2)

-- 1) map center over Window.dimensions to get a signal of origin positions
-- 2) map2 relativeMouse over the signal of origin positions and
--    Mouse.position to get signal of relative mouse positions
-- 3) map show over the signal of relative mouse positions to display them
main = Signal.map show (Signal.map2 relativeMouse (Signal.map center Window.dimensions) Mouse.position)

回答你的最后一个问题:Signal.map2 是你用来将 1 个函数映射到 2 个信号上的方法。对应的地图最多存在 map5.

信号导入行也可以改成

import Signal exposing ((<~), (~))

使用较短的信号映射语法,在这种情况下主线变为

main = show <~ (relativeMouse <~ (center <~ Window.dimensions) ~ Mouse.position)