Re: subscripts

new topic     » goto parent     » topic index » view thread      » older message » newer message

On Thu, 18 May 2000 01:47:10 +1200, jiri babor <jbabor at PARADISE.NET.NZ>
wrote:

>Carl, I would not say pedantic - negligent is the word! ;)
>The task was 'subscripting of sequences with *sequences*'.
>Read the specs!

Aah, sweet negligence. Especially when one is not the only guilty party:

Your while loop is semantically equivalent to my for loop. I've just added
a little error checking here and there to tidy the function up a little.
Otherwise they're exactly the same.

Neither function copes with the situation where 'b' is greater than the
depth/dimension of 'a' at the point it is accessed, though.

Moving swiftly along before things turn ugly; I think what we're trying to
implement here is some kind of associative array type...

global type aa(object x)
    if atom(x) then return 0 end if
    return remainder(length(x),2) = 0
end type

function aa_find(object index, aa array)
    integer pos
    pos = find(index, array)
    pos *= remainder(pos,2) -- make sure it's an index
    return pos
end function

global function aa_index(aa array, object index)
    integer pos
    pos = aa_find(index, array)
    if pos then
        return array[pos+1] -- return the associated data
    end if
    return array[0] -- deliberate error -- or we could handle it...
    -- return {}
end function

global function aa_add(aa array, object index, object data)
    integer pos
    pos = aa_find(index, array)
    if pos then
        array[pos+1] = data
    else
        array = array & {index, data}
    end if
    return array
end function

global function aa_remove(aa array, object index)
    integer pos
    pos = aa_find(index, array)
    if not pos then return array end if
    array = array[1..pos-1] & array[pos+2..length(array)]
    return array
end function

sequence animal
aa noise

noise = {}
noise = aa_add(noise, "cat", "miaow")
noise = aa_add(noise, "dog", "woof")
noise = aa_add(noise, "pig", "oink")
noise = aa_add(noise, "cow", "moo")

animal = "dog" -- change this
printf(1, "My %s says \"%s!\"\n", {animal, aa_index(noise, animal)})
-- End of code --

There's plenty of cunning things we could do with this. Even going to
multidimensional associativity. Not something I want to think about right
now blink

HTH,
Carl

--
Heeeere .sig .sig .sig .siggy...

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu