function definition evaluates as an integer

1 view
Skip to first unread message

Sean McIlroy

unread,
Jul 31, 2008, 6:05:51 PM7/31/08
to KeyKit
HOLA

I MUST BE MISSING A PUZZLE PIECE. I'M TRYING TO DEFINE A FUNCTION BUT
I GET AN INTEGER INSTEAD. HERE'S THE CODE:

function iteminlist(item,list) #### WORKING
{
for (index in list) {if (list[index]==item) return(1)}
return(0)
}

function inlist(list) #### BROKEN (SEE BELOW)
{
function returnvalue(item) {return(iteminlist(item,list))}
return(returnvalue)
}

smallprimes = [0=2, 1=3, 2=5, 3=7, 4=11]
threeissmallprime = iteminlist(3,smallprimes) #### WORKING
notafunction = inlist(smallprimes) #### EVALUATES AS 45 (?!?)

WHY DOES THIS HAPPEN? IF IT HELPS, HERE'S WHERE I'M TRYING TO GO:

function closure(f,bindings)
{
function closed(...)
{
numargs = nargs() + sizeof(bindings)
args = bindings
argvindex = 0
for (i=0; i<numargs; i++) {if (!(i in args)) {args[i]=argv(argvindex+
+)}}
return(f(varg(args)))
}
return(closed)
}

#### ...AND THEN, FOR EXAMPLE:
issmallprime = closure(iteminlist,[1=smallprimes]))}
#### THIS IS A SYNTAX ERROR IF READ FROM FILE...
#### ...BUT THE RIGHTHAND-SIDE EVALUATES AS 1 IN THE INTERPRETER

I NEED TO CLEAR THIS HURDLE OR FIND A WAY AROUND IT IN ORDER TO GET
KEYKIT SPEAKING MY LANGUAGE. WHAT SHOULD I DO?

peace
stm

Tim Thompson

unread,
Jul 31, 2008, 7:17:55 PM7/31/08
to Sean McIlroy, KeyKit
> function inlist(list) #### BROKEN (SEE BELOW)
> {
> function returnvalue(item) {return(iteminlist(item,list))}
> return(returnvalue)
> }

You can't have nested functions/closures like that - all functions exist in
a single global scope. You can return a function value and dereference it,
as you're doing, and argv() and varg() can be used, as you're doing. You
could create a convention for a closure, perhaps - an array whose first
value is a function, and whose subsequent values are the initial arguments
to use when calling it. Then create a call_closure() function that
evaluates such arrays, adding on whatever additional arguments are passed to
it, e.g.

function call_closure(carr,...) {
f = carr[0]
i = 0
arr = []
for ( n=1; n<sizeof(carr); n++ ) {
arr[i++] = carr[n]
}
for ( n=1; n<nargs(); n++ ) {
arr[i++] = argv(n)
}
f(varg(arr))
}
function doit() {
for ( n=0; n<nargs(); n++ ) {
print("doit arg n=",n," = ",argv(n))
}
}
function sean() {
c = [0=doit,1=44,2=55]
call_closure(c,99)
}

The code in call_closure() is a little messier than it should be - it looks
like you can't combine the use of varg and "..." in a single function call,
but it's easy enough to just add them to the array you give to varg(), as
shown.

...Tim...

Reply all
Reply to author
Forward
0 new messages