(Crossposted到Reddit)
如何将已知长度列表转换为相同长度的元组?有没有办法使用applicatives这样做?
更具体地说,我使用Random.Pcg.independentSeed
从单个种子生成多个种子。然后我想将这些变量分配给几个变量:
import Random.Pcg as R
let
(seed1, seed2, seed3) =
R.step (R.list 3 R.independentSeed) seed
in
... use the 3 seeds
如果我需要第四个种子,我可以将“3”增加到“4”并在元组中添加另一个种子。
这是我提出的最好的:
let
seeds =
R.step (R.list 3 R.independentSeed) seed
|> Tuple.first
( seed1, seed2, seed3 ) =
case seeds of
[ seed1, seed2, seed3 ] ->
( seed1, seed2, seed3 )
_ ->
( R.initialSeed 0
, R.initialSeed 0
, R.initialSeed 0
)
in
...use the 3 seeds
没有通用的方法来创建一个返回不同长度的元组的函数。您可以使用applicatives来创建一些这样的帮助函数:
tuple2 : R.Generator a -> R.Generator (a, a)
tuple2 gen =
R.map (,) gen
|> R.andMap gen
tuple3 : R.Generator a -> R.Generator (a, a, a)
tuple3 gen =
R.map (,,) gen
|> R.andMap gen
|> R.andMap gen
tuple4 : R.Generator a -> R.Generator (a, a, a, a)
tuple4 gen =
R.map (,,,) gen
|> R.andMap gen
|> R.andMap gen
|> R.andMap gen