Random.Generate Int 的案例

case-of with Random.Generate Int

我是 elm 的新手。 Elm 版本是 0.19。我正在尝试使用 Ranndom.int 到 select 船型,但不知道该怎么做。 我应该如何处理 numToShip 函数?改变类型?

这是我的代码...

type ShipType
    = Battleship
    | Cruiser   
    | Destroyer 
    | Submarine 

numToShip : Int -> ShipType
numToShip num =
   case num of
     0 -> Destroyer
     1 -> Battleship
     2 -> Cruiser
     _ -> Submarine

shipName : ShipType -> String
shipName shipType =
  case shipType of
    Destroyer ->
        "Destroyer"
    Battleship ->
        "Battleship"
    Cruiser ->
        "Cruiser"
    Submarine ->
        "Submarine"

randomShip : String
randomShip =
  shipName (numToShip (Random.int 0 3) )

错误信息是:

The 1st pattern in this `case` causing a mismatch:

 146|   case num of

 147|>    0 -> Destroyer 

 148|     1 -> Battleship

 149|     2 -> Cruiser

 150|     _ -> Submarine

The first pattern is trying to match integers:
    Int

But the expression between `case` and `of` is:
    Random.Generator Int

这些永远无法匹配!模式是问题吗?还是表达方式?

Random.int does not return an Int, but a Generator Int. You'll then call Random.generateGenerator 转换为 Cmd,然后它将使用生成的值调用您的 update 函数。

Elm 的一个特点是所有函数都是,这意味着相同的输入总是产生相同的输出。由于每次调用该函数时都要求不同的值,因此您需要将该命令交给运行时,它可以处理请求的不纯性(这与您想要与外部世界通过 HTTP 或 JavaScript)。有关详细信息,请参阅 the Random example in the Elm Guide

或者,如果您愿意提供用于计算随机值的种子,则可以立即从 Generator 中获取一个值。您可以使用 Random.step, which takes a Generator and a Seed,并生成一个值 下一个种子,如果您需要多个值,您可以将其反馈给 step。如果能够 "replay" 您的随机值很有用,您可能只想这样做,因为保持 Seed 有点痛苦。否则,只需坚持使用 generate 来创建 Cmd.