Search code examples
nested-listselm

Elm : How to apply List.map on Nested List


This is the basic work i have done with simple List Float

renderCoordinates : List Float -> Html Msg
renderCoordinates coordinates =
    ol [ type_ "A"]
        (List.map (\coordinate -> li [] [text (String.fromFloat coordinate)]) coordinates)

When it comes to List (List(List Float)) and i am stuck. I am wonder if i can do it this way?

renderCoordinates : List (List(List Float)) -> Html Msg
renderCoordinates coordinates =
    ol [ type_ "A"]
        (List.map (List.map (\coordinate -> li [] [text (String.fromFloat coordinate)]) ) coordinates)

-- List.map (List.map (List.map (\coordinate -> li [] [text (String.fromFloat coordinate)]) ) ) coordinates doesnt work as well

Basically i wish to display each items in the list of List (List(List Float))... Any help is appreciate !

Updates

With the help of @Simon I made some modification of code to make it works like :

renderCoordinates : List (List (List Float)) -> Html Msg
renderCoordinates coordinates =
    let
        map1 : List (List (List Float)) -> List (Html Msg) 
        map1 lists =
            List.concatMap map2 lists

        map2 : List (List Float) -> List (Html Msg)
        map2 floats =
            List.map (\coordinate -> li [] [ text (Debug.toString coordinate) ]) floats
    in
    ol [ type_ "A" ]
        (map1 coordinates)

This will print A: [X, Y]


Solution

  • You need to do it in parts and concat the results at each stage

    renderCoordinates : List (List (List Float)) -> Html Msg
    renderCoordinates coordinates =
        let
            map1 : List (List Float) -> List (Html Msg)
            map1 lists =
                L.concatMap map2 lists
    
            map2 : List Float -> List (Html Msg)
            map2 floats =
                List.map (\coordinate -> li [] [ text (String.fromFloat coordinate) ]) floats
        in
        ol [ type_ "A" ]
            (List.concatMap map1 coordinates)