你如何迭代一个列表(也许是一个)

How do you iterate a List (Maybe a)

我有以下 graphQL 结果:

[Just { details = Just "Engine failure at 33 seconds and loss of vehicle", launch_year = Just "2006", links = Just { article_link = Just "https://www.space.com/2196-spacex-inaugural-falcon-1-rocket-lost-launch.html" }, mission_name = Just "FalconSat" }]

基于以下类型:

type alias Launch =
    { mission_name : Maybe String
    , details : Maybe String
    , launch_year : Maybe String
    , links : Maybe LaunchLinks
    }


type alias Launches =
    Maybe (List (Maybe Launch))


type alias LaunchLinks =
    { article_link : Maybe String
    }

我想 List.map 通过并在无序列表中显示结果。我从这个开始:

renderLaunch : Launches -> Html Msg
renderLaunch launches =
    div [] <|
        case launches of
            Nothing ->
                [ text "Nothing here" ]

            Just launch ->
                launch
                    |> List.map (\x -> x)
                    |> ul []

但是我一直收到这个错误:

This function cannot handle the argument sent through the (|>) pipe:

141| launch 142| |> List.map (\x -> x) 143| |> ul [] ^^^^^ The argument is:

List (Maybe Launch)

But (|>) is piping it a function that expects:

List (Html msg)

问题是 Just launch 案例需要导致 List (Html msg) 但代码导致不同类型被 returned.

当您使用 List.map (\x -> x) 时,它本质上是一个 no-op。您正在迭代 List (Maybe Launch) 和 return 同一件事。我建议创建另一个采用 Maybe Launch 值的函数并将其用作映射函数。例如:

displayLaunch : Maybe Launch -> Html Msg
displayLaunch launch =
    case launch of
        Nothing -> text "No launch"
        Just l -> text (Debug.toString l)

现在您可以将其插入您的映射函数:

Just launch ->
    launch
        |> List.map displayLaunch
        |> ul []

但是,哎呀!现在您收到一个新错误,指示:

The 2nd branch is:

    Html Msg

But all the previous branches result in:

    List (Html msg)

这里的问题是我们现在 return 从 Just launch 分支创建 ul,我们需要 return html 的列表.您可以使用 List.singleton 创建仅包含一项的列表:

Just launch ->
    launch
        |> List.map displayLaunch
        |> ul []
        |> List.singleton