如何理解Elm的unwrapUITreeNodeChild函数并转译为Python3?
Elm转Python3:理解并实现unwrapUITreeNodeChild函数
我一直试图理解以下Elm函数,觉得自己的解读有问题,正尝试把它转译为Python3:
type UITreeNodeChild = UITreeNodeChild UITreeNode unwrapUITreeNodeChild : UITreeNodeChild -> UITreeNode unwrapUITreeNodeChild child = case child of UITreeNodeChild node -> node
我能看出unwrapUITreeNodeChild函数接收类型为UITreeNodeChild的参数child,返回UITreeNode类型。我尝试用Python实现如下:
class UITreeNodeChild(Enum): UITreeNodeChild=UITreeNode def unwrapUITreeNodeChild(child: UITreeNodeChild) -> UITreeNode: if child is UITreeNodeChild: pass # 我完全不清楚这部分的实际含义。
我不理解函数剩余的逻辑,查阅Elm文档后对其中的模式匹配仍感困惑,似乎是将node传入UITreeNodeChild的定义中。我知道自己的实现有误,请问我忽略了什么关键点?
编辑:我意识到示例本质是要进行类型检查,需要确认类型后使用其内部属性,尝试改写为:
class UITreeNodeChild: pass def unwrapUITreeNodeChild(child: UITreeNodeChild) -> UITreeNode: if type(child) == UITreeNodeChild: pass
注:需要检查类型而非是否为同一对象。
关键点解析与正确实现
你误解了Elm中自定义类型的核心逻辑:
- Elm里的
type UITreeNodeChild = UITreeNodeChild UITreeNode是定义了一个带参数的联合类型:UITreeNodeChild既是类型名称,也是该类型唯一的构造函数——创建这个类型的实例时,必须传入一个UITreeNode对象作为参数,这个参数会被包裹在实例中。 - 你的Python尝试错误地用了枚举或空类,完全没体现“构造函数携带并存储数据”的核心特性。
正确的Python实现
# 先定义UITreeNode类(示例用空类,实际可根据业务需求补充属性/方法) class UITreeNode: pass class UITreeNodeChild: def __init__(self, node: UITreeNode): # 初始化时接收并存储UITreeNode实例 self.wrapped_node = node def unwrapUITreeNodeChild(child: UITreeNodeChild) -> UITreeNode: # 直接取出被包裹的UITreeNode实例返回 return child.wrapped_node
补充说明
- Elm的模式匹配
case child of UITreeNodeChild node -> node,本质就是解构构造函数创建的实例,取出其中包裹的node值,对应到Python就是访问实例的属性。 - 如果需要运行时类型校验,可以给函数添加检查逻辑:
def unwrapUITreeNodeChild(child: UITreeNodeChild) -> UITreeNode: if not isinstance(child, UITreeNodeChild): raise TypeError("参数必须是UITreeNodeChild类型") return child.wrapped_node
内容的提问来源于stack exchange,提问作者Fallenreaper
相关产品推荐
相关产品推荐

