Associative array/Creation: Difference between revisions

no edit summary
(Move Racket entry to appropriate section)
No edit summary
Line 264:
"sicko&mumps" = 7
"sicko&bromodrosis" = 8</pre>
 
 
=={{header|BASIC256}}==
<lang BASIC256>global values$, keys$
dim values$[1]
dim keys$[1]
 
call updateKey("a","apple")
call updateKey("b","banana")
call updateKey("c","cucumber")
 
gosub show
 
print "I like to eat a " + getValue$("c") + " on my salad."
 
call deleteKey("b")
call updateKey("c","carrot")
call updateKey("e","endive")
gosub show
 
end
 
show:
for t = 0 to countKeys()-1
print getKeyByIndex$(t) + " " + getValueByIndex$(t)
next t
print
return
 
subroutine updateKey(key$, value$)
# update or add an item
i=findKey(key$)
if i=-1 then
i = freeKey()
keys$[i] = key$
end if
values$[i] = value$
end subroutine
 
subroutine deleteKey(key$)
# delete by clearing the key
i=findKey(key$)
if i<>-1 then
keys$[i] = ""
end if
end subroutine
 
function freeKey()
# find index of a free element in the array
for n = 0 to keys$[?]-1
if keys$[n]="" then return n
next n
redim keys$[n+1]
redim values$[n+1]
return n
end function
 
function findKey(key$)
# return index or -1 if not found
for n = 0 to keys$[?]-1
if key$=keys$[n] then return n
next n
return -1
end function
 
function getValue$(key$)
# return a value by the key or "" if not existing
i=findKey(key$)
if i=-1 then
return ""
end if
return values$[i]
end function
 
function countKeys()
# return number of items
# remember to skip the empty keys (deleted ones)
k = 0
for n = 0 to keys$[?] -1
if keys$[n]<>"" then k++
next n
return k
end function
 
function getValueByIndex$(i)
# get a value by the index
# remember to skip the empty keys (deleted ones)
k = 0
for n = 0 to keys$[?] -1
if keys$[n]<>"" then
if k=i then return values$[k]
k++
endif
next n
return ""
end function
 
function getKeyByIndex$(i)
# get a key by the index
# remember to skip the empty keys (deleted ones)
k = 0
for n = 0 to keys$[?] -1
if keys$[n]<>"" then
if k=i then return keys$[k]
k++
endif
next n
return ""
end function</lang>
Output:
<pre>a apple
b banana
c cucumber
 
I like to eat a cucumber on my salad.
a apple
e endive
c carrot</pre>
 
=={{header|BBC BASIC}}==
Anonymous user