在 Elm 中生成带有多个参数的消息的命令

Generating a command with a message with more than one arguments in Elm

我正在学习 Elm 教程 Random,但在尝试 运行 将两个骰子放在一起时遇到了困难。

我修改了消息以传递两个号码:

type Msg
    = Roll
    | NewFace Int Int

然后我需要生成在 update 函数中发送消息的命令:

(model, Random.generate NewFace (Random.int 1 6))

问题是这个构造失败了:

-- error: Function `generate` is expecting 2 arguments, but was given 3.
(model, Random.generate NewFace (Random.int 1 6) (Random.int 1 6))

起初我尝试用括号将最后一个参数分组:

-- same error as before plus: 
-- The type annotation is saying:
--     Msg -> Model -> ( Model, Cmd Msg )
-- But I am inferring that the definition has this type:
--     Msg -> Model -> ( Model, Cmd (Int -> Msg) )
(model, Random.generate NewFace ((Random.int 1 6) (Random.int 1 6)))

然后我发现有一个Random.pair函数:

-- still complaining about update's signature and moreover
-- Function `generate` is expecting the 2nd argument to be:
--    Random.Generator Int
-- But it is:
--    Random.Generator ( Int, Int )

(model, Random.generate NewFace (Random.pair (Random.int 1 6) (Random.int 1 6)))

我确信我遗漏了一些微不足道的东西,尽管这是我在 Elm 的第一天并且越来越具有挑战性。

谢谢

Random.pair 生成一个元组,因此您的 NewFace 消息必须接受一个元组作为参数。尝试将其更改为:

type Msg
  = Roll
  | NewFace (Int, Int)