Page 1 of 1
defining functions inside functions
Posted: Tue Nov 03, 2009 5:17 pm
by cormullion
Is it useful to be able to define functions inside other functions? (It's already possible in newLISP, but I don't know why you'd want to.)
Re: defining functions inside functions
Posted: Tue Nov 03, 2009 9:22 pm
by Kazimir Majorinc
It is easy to find examples of anonymous functions. For example, many times map is used with some anonymous function.
I have used named functions few times. For example, (protect2 'f '(x y z)) will define new, "protected" version of the function f - and assign it to the name f.
Also (debug-wrap f), or (multiloop 'dolist) that returns dolist-multi which does the same as dolist, but accepts multiple variables (dolist-multi((i j k) '(1 2 4 8)) ...
Also, in hset that (hset '*) defines function set* such that (set* 'x 3) is equivalent of (set 'x (* x 3)) ...
(These functions are described in my blog and they are part of the Instprog.default-library.lsp, on my site)
Re: defining functions inside functions
Posted: Tue Nov 03, 2009 10:00 pm
by cormullion
Hi Kazimir! Yes - I remember hset now... Your coding style doesn't use define much, so I sometimes can't work out whether you're using an equivalent or not... I understand about anonymous functions, but wondered about using define to define nested functions... I think they're just added to the current context as usual...
Re: defining functions inside functions
Posted: Wed Nov 04, 2009 6:20 am
by kosh
You mean like this?
Code: Select all
(define (mapflat f lst)
(let ((visitor (lambda (x) ; define internal function
(cond ((atom? x) x)
("else" (apply f (map visitor x)))))))
(visitor lst)))
(mapflat + '(1 2 3 (4 5 6 (7 8 9) 10)))
;=> 55
visitor
;=> nil
---
kosh
Re: defining functions inside functions
Posted: Wed Nov 04, 2009 4:41 pm
by m35
Maybe if there are two very different tasks that should occur within a loop depending on a state, you could create functions instead of having a conditional inside the loop?
Code: Select all
(define (fishy-function b?)
(if b?
(define (dafunc) (println "Doing something"))
(define (dafunc) (println "Doing something completely different"))
)
(dotimes (i 10)
(dafunc)
)
)
Re: defining functions inside functions
Posted: Wed Nov 04, 2009 5:04 pm
by cormullion
kosh wrote:You mean like this?
Not really.., :)
I'm OK with anonymous functions, but I've seen some Lisp or Scheme code with a named function defined (using
define) inside another named function. But in newLISP the inner function seems to be treated as just another function definition, so there seems to be little advantage to doing it the following way - your version is better.
Code: Select all
(define (mapflat f lst)
(let ((dummy 0))
(define (visitor x)
(cond ((atom? x) x)
("else" (apply f (map visitor x)))))
(visitor lst)))
But m35 has an interesting example!