defining functions inside functions

Started by cormullion, November 03, 2009, 09:17:44 AM

Previous topic - Next topic

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.)

Kazimir Majorinc

#1
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)
http://kazimirmajorinc.com/\">WWW site; http://kazimirmajorinc.blogspot.com\">blog.

cormullion

#2
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...

kosh

#3
You mean like this?


(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

m35

#4
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?


(define (fishy-function b?)
(if b?
(define (dafunc) (println "Doing something"))
(define (dafunc) (println "Doing something completely different"))
)
(dotimes (i 10)
(dafunc)
)
)

cormullion

#5
Quote from: "kosh"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.


(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!