Return List with Single Element

Hi,

I am new to Elm and I have a function that returns a list with elements.
I want to edit this function to return a single element list with a text if the list is empty.
E.g “Could not retrieve list for you”

Original code

viewResults : RemoteData.WebData (List KartverketResult) -> Html Msg
viewResults data =
    case data of
        RemoteData.NotAsked ->
            text ""

        RemoteData.Loading ->
            text ""

        RemoteData.Success results ->
            results
                |> List.map viewResult
                |> ul [ class "col-1of1 border_search_list" ]

        RemoteData.Failure e ->
            text "Sorry, could not retrieve list. Some error occurde"

Ish what I wish, that Elm does not want to do for me:

viewResults : RemoteData.WebData (List KartverketResult) -> Html Msg
viewResults data =
    case data of
        RemoteData.NotAsked ->
            text ""

        RemoteData.Loading ->
            text ""

        RemoteData.Success results ->
            if List.isEmpty results then
                li [ class "col-1of1 txt-primary padding-5" ] [ text "List is empty, Please check your spelling" ] 
                |> ul [ class "col-1of1 border_search_list" ]

            else
                results
                    |> List.map viewResult
                    |> ul [ class "col-1of1 border_search_list" ]

        RemoteData.Failure e ->
            text "Sorry, could not retrieve list. Some error occurde"

tl;dr

RemoteData.Success results ->
            results
                |> List.map viewResult
                |> ul [ ]

Code above to code below

RemoteData.Success results ->
            if List.isEmpty results then
                li [ ] [ text "List is empty, Please check your spelling" ] 
                |> ul [ ]

            else
                results
                    |> List.map viewResult
                    |> ul [ ]

Kind Regards,
Simon

if List.isEmpty results then
    li [] [ text "List is empty, Please check your spelling" ] 
        |> ul []

I think the problem here is that ul [] needs a list of lis, and you’re only giving it a single li. So you need to wrap your li in a list.

Here are two ways to do that:

if List.isEmpty results then
    [ li [] [ text "List is empty, Please check your spelling" ] ]
        |> ul []

or:

if List.isEmpty results then
    li [] [ text "List is empty, Please check your spelling" ] 
        |> List.singleton
        |> ul []

Hello Rasputin303,

Thank you so much!
Both of these solutions worked exactly how I wanted.

Hope you have a nice day,
Warm regards,
Simon

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.