0

I have some codes like follow:

keys: LINKED_LIST[K]
...
test
local
    tempK:K
    tempI:INTEGER
do
...
across
    keys as cursor
loop
    tempK := cursor.item
    if tempK ~ 1 then
       tempI := tempK
    end
end
...
end

"cursor.item" is type of "K". However, the real value inside there is integer type.

thus, "if tempK ~ 1 then" works fine. But "tempI := tempK" doesn't work.

How can I convert tempK's K type to integer? so that it can compile?

Miku
  • 41
  • 1
  • 5

1 Answers1

1

In this particular case, where you know that tempK is 1, tempI := 1 will do.

If the idea is to initialize tempI as soon the values stored in the list are of type INTEGER, there are several ways. One is to use an object test:

if attached {INTEGER} tempK as i then
    tempI := i
end

However, in this case the test is performed for every element, i.e. inefficient. Changing the code to test for the list type before the loop will help:

if attached {LINKED_LIST [INTEGER]} keys as integer_keys then
    ...
    across
        integer_keys as cursor
    loop
        tempI := cursor.item
    end
    ...
end

If the only operation in the loop is the assignment, the equivalent code is to take just the last element of the list:

...
if not keys.is_empty and then attached {LINKED_LIST [INTEGER]} keys as integer_keys then
    tempI := integer_keys.last
end
...

Instead of specialization, the code could also be generalized to take a generic agent that will be passed the key, and the client will supply the procedure to handle the key. But this might be too much, depending on what is the purpose of the task you are solving.

Alexander Kogtenkov
  • 5,770
  • 1
  • 27
  • 35