了解Elm中的通用联合类型 [英] Understanding generic union types in Elm

查看:67
本文介绍了了解Elm中的通用联合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解 Html msg 类型到底是什么,或如何使用它。我在VirtualDom.elm中找到了这行代码,其中 Html msg 似乎是以下内容的别名:

I'm having some trouble understanding what exactly the Html msg type is, or how it gets used. I found this line of code in VirtualDom.elm, which Html msg seems to be an alias of:

type Node msg = Node

一种类型参数, msg ,另一种情况不包含任何其他信息。我想知道:

This looks like a generic union type with one type parameter, msg, and one trivial case that holds no additional information. I'm wondering:


  1. div 函数如何构造这些对象之一

  2. 如何使用这种对象?

  3. 如何使用这种对象?

  4. 用户定义这样的类型是否有价值?或者 Html msg 仅仅是支持Elm编译器/运行时的一种神奇类型?

  1. How does the div function construct one of these objects?
  2. How does an object like this get used?
  3. How could an object like this get used?
  4. Is there any value for a user to define a type like this, or is Html msg just a magical type to support the Elm compiler/runtime?


推荐答案

HTML msg Node msg 的http://guide.elm-lang.org/types/type_aliases.html rel = noreferrer>类型别名通用联盟类型

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

仅对<$ c $进行推理c> Elm Architecture上下文中的节点msg 类型签名,其中应用程序的所有输入( Http.App.programWithFlags 的标志除外)为发生

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 类型变量在 Node msg 中只是暗示您一个想法,即来自DOM子树的所有消息都应属于一个联合类型。

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



如何 div 函数使用通用联合类型



Elm编译器知道,当您的DOM树正确时,感谢 msg 类型变量在Elm Architecture上下文中。

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.

在JavaScript世界中, Node 值为 Node msg 联合类型用以下结构表示对象:

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
}



< h3>如何使用通用联合类型

大多数复杂的核心数据结构都是使用通用联合类型实现的,请检查也许词典以激发灵感。

HTML消息尤其神奇,但是您可以实现一些有趣的结构,例如链接列表或其他类似树的结构。

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)

这篇关于了解Elm中的通用联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆