首页 > 解决方案 > 列表中元素的长度

问题描述

假设我有列表 ["foo", "bar", "othercoolword"],我想知道每个元素的长度。我会做

map length ["foo", "bar", "othercoolword"]

然后它返回 [3,3,13]。但是,如果我在列表中有一个列表,例如

[["f","bee","oba"],["aloo","d","e"],["xnx","y","z"]]

我希望它返回 [[1,3,3],[4,1,1],[3,1,1]]。然后对该列表中的每个列表取最大值。这会给我[3,4,3]。

长话短说:我对列表中的这些列表感到困惑。有没有一种简单的方法可以做到这一点?

标签: haskell

解决方案


是的,很简单。观察

map length ["foo", "bar", "othercoolword"]
=>
           [3    , 3    , 13             ]

map length [["f","bee","oba"],["aloo","d","e"],["xnx","y","z","w"]]
=>
           [3                ,3               ,4                  ]

map length  ["f","bee","oba"]
=>
            [1  ,3    ,3    ]

map length                    ["aloo","d","e"]
=>
                              [4     ,1  ,1  ]

map length                                     ["xnx","y","z","w"]
=>
                                               [3    ,1  ,1  ,1  ]

以便

map (map length)             [["aloo","d","e"],["xnx","y","z","w"]]
=>
                             [[4     ,1  ,1  ],[3    ,1  ,1  ,1  ]]

接着

map maximum                  [[4     ,1  ,1  ],[3    ,1  ,1  ,1  ]]
=>
                             [ 4              , 3                 ] 

因此,只需命名您的临时变量,然后随意使用它们。


推荐阅读