Thursday, June 5, 2008

To Do: If Only ...

One of the simplest and most pervasive macros in arc is "do". "do" is useful when you need to evaluate a sequence of expressions, but you only have room for one. A common case is when evaluating conditionals:



(if a b
c d
e)

This corresponds to the following in java:
if (a) { 
return b;
} else if (c) {
return d;
} else {
return e;
}


In java, we can execute as many statements as we desire within a { } block; arc however allows only a single expression as return value. So if we wanted



if (a) { 
b();
c();
return d;
} else if (e) {
return f;
} else {
return g;
}


we can't just write



(if a b c d
e f
g)


Hence, do.



(if a (do b c d)
e f
g)


do expands into a call to a no-arg function containing b c d -



((fn () b c d))


- it defines an anonymous zero-arg function and immediately calls it. Hence, b c d are grouped in a single expression, and will work as desired inside a conditional:



(if a ((fn () b c d))
e f
g)

1 comment:

Berthold Hanisch said...


Sweet blog! I found it while searching on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I've been trying for a while but I never seem to get there! Appreciate it www.gmail.com login