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

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
    
  • 处理潜在未知类型的表达式的常见做法是访问者模式,该模式处理已知情况并回退到未知情况的默认值。

是否可以将 Alexander 的解决方案放入 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