Arc Forumnew | comments | leaders | submitlogin
Found a problem with the order in which functions are defined
1 point by croach 6097 days ago | 2 comments
I just ran into an error with the order in which a set of functions were defined in my code. Here is an example of a simplistic REPL session that reproduces this error:

  arc> (def hello () (blankpage (pr "Hello world")))
  #<procedure: hello>
  arc> (mac blankpage body `(tag html (tag body ,@body)))
  #3(tagged mac #<procedure>)
  arc> (hello)
  Hello world
  Error: "Function call on inappropriate object #3(tagged mac #<procedure>) (\"Hello world\")"
  arc> (def hello () (blankpage (pr "Hello world")))
  *** redefining hello
  #<procedure: hello>
  arc> (hello)
  <html><body>Hello world</body></html>"</"
  arc> 
So, it looks like Arc acts a bit like C in that all functions must defined before they are used. The compiler doesn't complain whenever you define a function that uses an, as yet, undefined function, but when you try to execute it, you'll get the "Function call on inappropriate object" error.

Am I the only one that has run into this problem, and if so, am I just doing something wrong here or is this actually an error that needs fixing?



7 points by sacado 6097 days ago | link

Macros have to be defined before they are used in a function, because they are expanded during the definition of the function.

Example :

  (def hello () (blankpage (pr "Hello world")))
  => def is a macro, evaluated as (set hello (fn () (blankpage (pr "Hello world"))))
Once the function is "compiled", no macro expansion will ever happen. So, when you call 'hello, it's looking for a function named 'blankpage and cannot find it.

  (mac blankpage body `(tag html (tag body ,@body)))
  => new macro saved

  (def hello () (blankpage (pr "Hello world")))
  => def and blankpage are macros, expansion performed, evaluated as 
  => (set hello (fn () (tag html (tag body (pr "Hello world")))))
  => tag is a macro, so another expansion has to be performed, etc.
Here, all macros are evaluated, only function calls are left in the compiled form. Thus, if you redefine 'blankpage or any other macro, don't forget to redefine all associated functions too.

But it does not apply to functions. They can be defined in any order.

-----

2 points by croach 6097 days ago | link

That's quite interesting. After reading through your explanation it makes perfect sense why I am running into this problem. Thanks for the answer and for such a fast reply to my query.

-----