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

时间:2016-08-20 19:59:06

标签: svg elm

我正尝试使用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类型从地图中取出而不是List?

错误讯息:

    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.

1 个答案:

答案 0 :(得分:3)

您可以将列表连接在一起,如下所示:

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)