Function from symbol?

Q&A's, tips, howto's
Locked
jeremyc
Posts: 33
Joined: Wed Dec 06, 2006 3:33 am

Function from symbol?

Post 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

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post 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

jeremyc
Posts: 33
Joined: Wed Dec 06, 2006 3:33 am

Post 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           ")

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post 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

Locked