Home > other >  Length of an element in a list in a list
Length of an element in a list in a list

Time:09-22

Let's say i have the list ["foo", "bar", "othercoolword"], and i want to know the length of each element. I would do

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

and it then returns [3,3,13]. But what if i have a list within a list, so for example

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

I want it to return [[1,3,3],[4,1,1],[3,1,1]]. And then take the maximum over each list inside this list. Which would give me [3,4,3].

Long story short: i'm confused with these lists inside lists. Is there an easy way of doing this?

CodePudding user response:

Yes, simple. Observe

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  ]

so that

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

and then

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

So just name your interim variables, and use them as you will.

CodePudding user response:

You'll want to use map twice, first on the outer list, then on the inner ones. With an anonymous function you could do:

   lengthInnerList list = map (\x -> map (length) x) list

Alternatively you could do it explicitly like this:

outer list = map (inner) list
inner x = map length x

Then apply the maximum function on that list.

CodePudding user response:

For each sublist in our list we need to calculate the length of its items with a map …, and then calculate the maximum of these lengths with another function with signature Ord a => [a] -> a. If we do that for each sublist, we thus get:

--   ↓       ↓ left as an exercise
map (… . map …) [["f","bee","oba"],["aloo","d","e"],["xnx","y","z"]]

Where I leave implementing the parts as an exercise. The first one has as signature [Int] -> Int and should determine the maximum of a list of Ints, the second needs to convert a String to an Int that determines the length of the string.

If a sublist is empty then calculating the maximum of the lengths of the elements of that sublist, will raise an error, since one can not determine the maximum of an empty list. Maybe it is therefore better to return a value of type [Maybe Int] that can be Nothing if there are no items in the sublist.

  • Related