Tree Traverse

Whatever is on your mind, whether Lisp related or not.

Tree Traverse

Postby farid.hendi » Mon Sep 20, 2010 10:41 am

Hi , I'm new in LISP.I saw the solution for Binary tree traverse , but I don't understand "FUN" in this problem . Could you please help me ?! :oops:

Code: Select all
(defstruct (btnode)
  (val nil)
  (left nil)
  (right nil))

;; naive traversal functions
(defun traverse-pre-order (node fun)
  (if node
      (progn
        (apply fun (list node))
        (if (btnode-left node)
            (traverse-pre-order (btnode-left node) fun))
        (if (btnode-right node)
            (traverse-pre-order (btnode-right node) fun)))))

(defun traverse-in-order (node fun)
  (if node
      (progn
        (if (btnode-left node)
            (traverse-in-order (btnode-left node) fun))
        (apply fun (list node))
        (if (btnode-right node)
            (traverse-in-order (btnode-right node) fun)))))

(defun traverse-post-order (node fun)
  (if node
      (progn
        (if (btnode-left node)
            (traverse-post-order (btnode-left node) fun))
        (if (btnode-right node)
            (traverse-post-order (btnode-right node) fun))
        (apply fun (list node)))))


[edited to put the code in a "[code]" block -- nuntius]
farid.hendi
 
Posts: 1
Joined: Mon Sep 20, 2010 10:36 am

Re: Tree Traverse

Postby nuntius » Mon Sep 20, 2010 8:37 pm

In this code, FUN is a variable that stores a function. FUNCALL or APPLY then call the function with its arguments.

It is common to pass functions as arguments in lisp. It is less common in C/C++ or Java because they do not provide good support for the idea.
User avatar
nuntius
 
Posts: 498
Joined: Sat Aug 09, 2008 10:44 am
Location: Burlington, MA


Return to The Lounge

Who is online

Users browsing this forum: No registered users and 1 guest