繁体   English   中英

有没有办法为参数指定各种类型

[英]Is there a way to specify various types for a parameter

有没有办法将类型的一致性限制为类型的集合?

让我举例说明:

give_foo (garbage: ANY): STRING
    do
        if attached {STRING} garbage as l_s then
            Result := l_s
        elseif attached {INTEGER} garbage as l_int then
            Result := l_int.out
        elseif attached {JSON_OBJECT} garbage as l_int then
            Result := l_int.representation
        elseif attached {RABBIT} garbage as l_animal then
            Result := l_animal.name + l_animal.color
        else
            Result := ""
            check
                unchecked_type_that_compiler_should_be_able_to_check_for_me: False
            end
        end
    end

我不能做类似的事情(就像转换函数可以做的那样)

give_foo (garbage: {STRING, INTEGER, JSON_OBJECT, RABBIT}): STRING
    do
        if attached {STRING} garbage as l_s then
            Result := l_s
        elseif attached {INTEGER} garbage as l_int then
            Result := l_int.out
        elseif attached {JSON_OBJECT} garbage as l_int then
            Result := l_int.representation
        elseif attached {RABBIT} garbage as l_animal then
            Result := l_animal.name + l_animal.color
        else
            Result := ""
            check
                unchecked_type_that_compiler_should_be_able_to_check_for_me: False
            end
        end
    end

或类似的东西

not_garbage_hash_table: HASH_TABLE[{INTEGER, STRING, ANIMAL}, STRING]

由于以下几个原因,不支持符合类型集合:

  • 在这种类型的表达式上调用特征变得不明确,因为相同的名称可能指代完全不相关的特征。
  • 在一种情况下,我们需要类型的总和(不相交联合),在第二个 - 普通联合中,在第三个 - 交集等。然后,可能会有组合。 人们需要一个建立在一个变得过于复杂的类型系统之上的代数。
  • 如果需要检查参数是否为预期类型之一,则可以使用以下前提条件:

     across {ARRAY [TYPE [detachable ANY]]} <<{detachable STRING}, {INTEGER}, {detachable JSON_OBJECT}>> as t some argument.generating_type.conforms_to (t.item) end
  • 处理潜在未知类型表达式的常见做法是访问者模式,该模式处理已知情况并回退到未知情况的默认值。

可能将亚历山大的解决方案放在 BOOLEAN 查询中,以便可以重用?

is_string_integer_or_json_object (v: detachable ANY): BOOLEAN
         -- Does `v' conform to {STRING}, {INTEGER}, or {JSON_OBJECT}?
    do
       across {ARRAY [TYPE [detachable ANY]]}
        <<{detachable STRING}, {INTEGER}, {detachable JSON_OBJECT}>> as t
       some v.generating_type.conforms_to (t.item) end
    end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM