我希望能够将列表拆分为多个列表。
我假设这需要存储在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
答案 0 :(得分: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 :(得分:1)
榆木0.19的更新答案
import List.Extra as E
E.groupsOf 3 (List.range 1 10)
--> [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]