在 Elm 中将列表转换为元组
Converting a List into a Tuple in Elm
(Crossposted 到 Reddit)
如何将已知长度的列表转换为相同长度的元组?有没有办法使用应用程序来做到这一点?
更具体地说,我正在使用 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
没有通用的方法来创建 returns 不同长度元组的函数。您可以使用 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
(Crossposted 到 Reddit)
如何将已知长度的列表转换为相同长度的元组?有没有办法使用应用程序来做到这一点?
更具体地说,我正在使用 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
没有通用的方法来创建 returns 不同长度元组的函数。您可以使用 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