Elm:将列表拆分为多个列表

Elm: Split list into multiple lists

我希望能够将一个列表分成多个列表。 我假设这需要存储在 tuple 中 - 尽管不完全确定。

说我这群8个人

users =
  ["Steve", "Sally", "Barry", "Emma", "John", "Gustav", "Ankaran", "Gilly"]

我想将它们分成特定数量的组。 例如,2 人、3 人或 4 人的团体。

-- desired result

( ["Steve", "Sally", "Barry"]
, ["Emma", "John", "Gustav"]
, ["Ankaran", "Gilly"]
)

这个问题的第 2 部分是,您将如何迭代并呈现不同长度的元组的结果?

我在玩这个例子,使用 tuple-map 但它似乎只期望有 2 个值的元组。

import Html exposing (..)
import List

data = (
  ["Steve", "Sally", "Barry"]
  , ["Emma", "John", "Gustav"]
  , ["Ankaran", "Gilly"]
  )

renderLI value =
  li [] [ text value ]

renderUL list =
  ul [] (List.map renderLI list)

main =
    div [] (map renderUL data)

-- The following taken from zarvunk/tuple-map for examples sake

{-| Map over the tuple with two functions, one for each
element.
-}
mapEach : (a -> a') -> (b -> b') -> (a, b) -> (a', b')
mapEach f g (a, b) = (f a, g b)

{-| Apply the given function to both elements of the tuple.
-}
mapBoth : (a -> a') -> (a, a) -> (a', a')
mapBoth f = mapEach f f

{-| Synonym for `mapBoth`.
-}
map : (a -> a') -> (a, a) -> (a', a')
map = mapBoth

I'd like to be able to split a list up into multiple lists. I'm assuming this would need to be stored in a tuple - although not completely sure.

元组携带物品的数量是固定的。您不能拥有接受任何大小元组的函数。

听起来您想要更灵活的东西,例如列表列表。您可以像这样定义一个 split 函数:

import List exposing (..)

split : Int -> List a -> List (List a)
split i list =
  case take i list of
    [] -> []
    listHead -> listHead :: split i (drop i list)

现在您已经有了一个函数,可以将任何大小的列表拆分为包含所请求大小的列表的列表。

split 2 users == [["Steve","Sally"],["Barry","Emma"],["John","Gustav"],["Ankaran","Gilly"]]
split 3 users == [["Steve","Sally","Barry"],["Emma","John","Gustav"],["Ankaran","Gilly"]]

您的 Html 渲染现在变得更简单了,因为您只需要处理列表的列表:

import Html exposing (..)
import List exposing (..)

split : Int -> List a -> List (List a)
split i list =
  case take i list of
    [] -> []
    listHead -> listHead :: split i (drop i list)

users =
  ["Steve", "Sally", "Barry", "Emma", "John", "Gustav", "Ankaran", "Gilly"]

renderLI value =
  li [] [ text value ]

renderUL list =
  ul [] (List.map renderLI list)

main =
    div [] (map renderUL <| split 3 users)

Elm 0.19 的更新答案

import List.Extra as E 

E.groupsOf 3 (List.range 1 10)
--> [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]