Page 1 of 1

Function from symbol?

Posted: Wed Feb 21, 2007 8:02 pm
by jeremyc
How can I:

Code: Select all

(define (greet who) (print "Hello " who))
(set 'lst '((name "John" who) (age 10)))
((lst 0 2) (lst 0 1))
In other words, reference a dynamic function inside a quoted list. The real reason for this is a process I created for parsing fixed width files:

Code: Select all

(define (special-conversion-function str) (do-something str))
(set 'layout '((name 10) (dob 6 special-conversion-function) (country 2)))
(import-data "file.txt" layout)
Now, the import-data function recognizes that dob requires a special conversion by the inclusion of another parameter in the fixed width format specification. I want import-data to then call the function "special-conversion-function" but I am failing to make it work.

Thanks,

Jeremy

Posted: Wed Feb 21, 2007 9:10 pm
by Lutz
not sure what you mean, but you can pass functions as parameters like this:

Code: Select all

> (define (do-func foo arg) (foo arg))
(lambda (foo arg) (foo arg))
> (do-func upper-case "hello")
"HELLO"
> 
and you could pass user defined functions the same way.

Or when your function is inside a list as a symbol:

Code: Select all

> (define (do-func foo arg) (set 'func (eval (first foo))) (func arg))
(lambda (foo arg) (set 'func (eval (first foo))) (func arg))
> (do-func '(upper-case lower-case) "hello")
"HELLO"
> 
Lutz

Posted: Wed Feb 21, 2007 9:21 pm
by jeremyc
Lutz wrote:not sure what you mean, but
Hm, my code was incorrect above. I simplified:

Code: Select all

(set 'lst '((name 20 trim) (age 5 int)))
(print ((lst 0 2) "JEREMY           ") "\n")

;; Desired output: JEREMY\n
Right now the output is:

Code: Select all

invalid function in function print : ((lst 0 2) "JEREMY           ")

Posted: Wed Feb 21, 2007 9:35 pm
by Lutz
one more level to peel off :)

Code: Select all

>(set 'lst '((name 20 trim) (age 5 int)))  
(print ((eval (lst 0 2)) "JEREMY           ") "\n")
JEREMY
"\n"
> 
Lutz