Understanding generic union types in Elm

房东的猫 提交于 2019-12-03 10:18:11

Html msg is a Type Alias for Node msg, which is a Generic Union Type

Union Type Node msg

It only makes sense to reason about Node msg type signature in a context of Elm Architecture, where all input for your application, except flags for Http.App.programWithFlags, is happening through messages.

msg type variable in Node msg is only hinting you towards the idea, that all messages from your DOM sub-tree should belong to a single union type.

node
    :  String
    -> List (Attribute msg)
    -> List (Html msg)  -- List of children nodes with a msg
    -> Html msg         -- Produced DOM node

How div function uses generic Union Types

Thanks to msg type variable, Elm compiler knows, when your DOM tree is correct in the context of Elm Architecture.

In JavaScript world Node value of Node msg Union Type is representing the object with the following structure:

{  
   "type":"node",
   "tag":"div",
   "facts":{},            // Attributes and DOM events
   "children":[],         // Children, have the same structure
   "descendantsCount": 0  // Used for Virtual DOM diffing
}

How you can use generic Union Types

Most of the complex core data structures are implemented using generic Union Types, check Maybe or Dict to get inspired.

Html msg and user-defined generic Union Types

Html msg in particular is somewhat magical, but you can implement some interesting structures, like linked lists or other tree-like structures.

type List a =
  Empty | Node a (List a)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!