榆树:将列表拆分成多个列表

问题描述 投票:3回答:2

我希望能够将列表拆分为多个列表。我假设这需要存储在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
elm
2个回答
11
投票

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

元组是固定的,它们可以携带的东西数量。你不能拥有一个接受任何大小元组的函数。

听起来你想要更灵活的东西,比如列表清单。你可以像这样定义一个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)

1
投票

更新了Elm 0.19的答案

import List.Extra as E 

E.groupsOf 3 (List.range 1 10)
--> [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
© www.soinside.com 2019 - 2024. All rights reserved.