我希望能够将一个列表拆分为多个列表。 我假设这需要存储在元组中 - 尽管不完全确定。
假设我有这个 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:将列表拆分为多个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37361229/