将列表转换为Elm中的元组

时间:2018-01-04 13:39:54

标签: tuples elm applicative

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

1 个答案:

答案 0 :(得分:3)

没有通用的方法来创建一个返回不同长度的元组的函数。您可以使用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