如何在 Elm 视图中迭代列表?

How to iterate over a list in an Elm view?

我正在尝试通过以下方式在 Elm 中使用视图将矩形添加到 SVG:

view : Model -> Html Msg
view model =
  let
      log1 = Debug.log "Time: " model.time
      log2 = Debug.log "Coords: " model.coordinates
      rects = [ ("200", "200"), ("210","201"), ("220", "202") ]
  in
    svg
    [ width "700", height "700", viewBox "0 0 500 500" ]
        [ rect [ x "100", y "100", width "600", height "600", fill "gray" ] []
        , List.map (\ coord -> (rect [ x (fst coord), y (snd coord), width "1", height "1", fill "black" ] [])) rects
        ]

有没有办法从地图中获取 VirtualDom.Node 类型而不是列表?

错误信息:

    The 1st element has this type:

        VirtualDom.Node a

    But the 2nd is:

        List (Svg a)

Hint: All elements should be the same type of value so that we can iterate
through the list without running into unexpected values.

您可以像这样将列表连接在一起:

svg
[ width "700", height "700", viewBox "0 0 500 500" ]
    ([ rect [ x "100", y "100", width "600", height "600", fill "gray" ] [] ]
      ++ List.map (\ coord -> (rect [ x (fst coord), y (snd coord), width "1", height "1", fill "black" ] [])) rects)

由于第一个列表是单个元素,您也可以使用 cons 运算符

svg
[ width "700", height "700", viewBox "0 0 500 500" ]
    (rect [ x "100", y "100", width "600", height "600", fill "gray" ] []
      :: List.map (\ coord -> (rect [ x (fst coord), y (snd coord), width "1", height "1", fill "black" ] [])) rects)