1

Discovering late (used to define classes instead) TUPLES and looking through the documentation I was wondering if there is a mechanism to get the right type of a given TUPLE. The goal is both anchoring its types and avoid having to test its type before getting an item. Is there a language mechanism?

I also found few documentation about them, maybe I'm not looking at the right place.

For the following code I'd like to tell like tuple_items.types[1] and tuple_items.typed_item (1)

use_it
    do
        if attached {STRING} tuple_items.item (1) as l_tuple_item_1 then
            io.put_string (l_tuple_item_1)
        end
        if attached {DATE} tuple_items.item (1) as l_tuple_item_2 then
            io.put_string (l_tuple_item_2.out)
        end
        - ...
    end

tuple_items: TUPLE[STRING, DATE, INTEGER]
    local
        l_first: STRING -- like tuple_items.first?
    do
        Result := [l_first, create {DATE}.make_now, 1]
    end
U. Windl
  • 3,480
  • 26
  • 54
Pipo
  • 4,653
  • 38
  • 47

2 Answers2

3

A named tuple enables accessing the tuple items by name:

tuple_items: TUPLE [name: STRING; date: DATE; quantity: INTEGER]

Then, the feature use_it simplifies to

        io.put_string (tuple_items.name)
        io.put_string (tuple_items.date.out)

At the moment, tuple item names cannot be used in an anchored type, so there is no way to specify the type of l_first relative to the type of the tuple item. A workaround might be adding an anchor

name_anchor: STRING
    require 
        is_callable: False
    do
        check from_precondition: False then end
    end

and using it in anchored types, including the tuple declaration:

tuple_items: TUPLE [name: like name_anchor; date: DATE; quantity: INTEGER]
    local
        l_first: like name_anchor
Alexander Kogtenkov
  • 5,770
  • 1
  • 27
  • 35
0

You may also use the anchor another way:

name_anchor: detachable STRING

Then the named-TUPLE reference changes slightly to:

tuple_items: TUPLE [name: attached like name_anchor]

If you want to ensure that name_anchor never becomes attached, you can add a class invariant:

invariant type_anchor_only: not attached name_anchor

This will prevent anything from trying to attach an object to your anchor. The downside is that this prevention code in the invariant is perhaps far removed from the location of the name_anchor feature in your code, which means another programmer may not easily pick up on the reason for the invariant. Hopefully, the tag on the contract helps to tell that story.

Liberty Lover
  • 844
  • 10
  • 12
  • @Pipo—by the way—I tend to always label my "type anchors" with a suffix such as `?_anchor`. As a naming convention, it provides a clue as to the expectations of using the feature only as a type anchor and never as a feature for storing data or in computations. – Liberty Lover Aug 20 '22 at 15:58