如何重复使用可扩展记录?

时间:2018-06-10 11:31:27

标签: recursion elm

我是榆树的初学者。我学会了如何重复记录,并创建可扩展的记录。我的目标应用程序具有树形数据,可以在多个树视图中呈现。

为了让Elm允许递归模型,需要

  • 儿童字段的联盟类型,
  • 可能在该类型定义中,
  • 如果需要Json解码,则为惰性匿名函数构造。

到目前为止一直很好,但我无法将递归与扩展相结合。下面是我到底有多远的最小化版本。此程序能够呈现两种示例类型之一(文件夹和注释),但不能同时呈现。 (请参阅评论为-- NOTE-- FOLDER)的行。

问题在于kids功能。 Elm不允许它生成两种不同的输出类型。我坚持要么重复代码,要么没有记录扩展。两者似乎都是炫耀者。

  • 有没有办法让这个,扩展和递归,没有代码重复?

Run on Ellie

module Main exposing (main)
import Html exposing (..)
import Maybe

-- MAIN

main = Html.beginnerProgram
  { model         = init
  , update        = update
  , view          = view
  }

-- MODEL

type alias Model =
  { folder  : Folder
  , note    : Note
  }

type alias Node a =
  { a | name     : String
      , children : Children a
  }

type alias Folder =
  { name     : String
  , children : ChildFolders
  }

type alias Note =
  { name     : String
  , children : ChildNotes
  }

type Children a   = Children a   (Maybe (List (Node a)))
type ChildFolders = ChildFolders (Maybe (List Folder))
type ChildNotes   = ChildNotes   (Maybe (List Note))

-- INIT

init : Model
init = Model
        (Folder "Parent F" someFolders)
        (Note   "Parent N" (ChildNotes Nothing))

someFolders : ChildFolders
someFolders = ChildFolders
  ( Just
    ( [ Folder "Child F1" (ChildFolders Nothing)
      , Folder "Child F2" (ChildFolders Nothing)
      , Folder "Child F3" (ChildFolders Nothing)
      ]
    )
  )

-- UPDATE

type Msg = NoOp

update : Msg -> Model -> Model
update msg model =
  case msg of
    NoOp -> model

-- VIEW

view : Model -> Html msg
view model =
  div []
  [ viewBranch model.folder    -- FOLDER
  -- , viewBranch model.note   -- NOTE
  ]

-- viewBranch : (?) -> Html msg
viewBranch node =
  uli
  ( text node.name
    ::  ( node
          |> kids
          |> List.map viewBranch
        )
  )

uli : List (Html msg) -> Html msg
uli items = ul [] [ li [] items ]

-- kids : (?) -> (?)
kids { children } =
  case children of
    (ChildFolders data) -> Maybe.withDefault [] data      -- FOLDER
    -- (ChildNotes   data) -> Maybe.withDefault [] data   -- NOTE

0 个答案:

没有答案