text:
Restricted minumum
You need to find the sum of minimum values of two list (same size) of small numbers. In a C like language, that could be expressed as:
v = min(a[0],b[0]) + min(a[1],b[1])+ min(a[2],b[2]) ...
The range of values is 0..7 and the 2 list can have up to 7 values. If you like, all the values in each list can be stored as a single 32 bit number.
My goal is avoiding branches in code, so the rules are

Single line expression,
No function calls or method calls (except for basic operations like sum, if your language mandate this),
No if statements, including things that compile to if statements such as ternary operators or "greater than" operators

Edit 1 To clarify, what I want is 'no branches in code'. So, no if, no calls (function of methods). Loops with fixed ranges (0..7) could be OK because can be unrolled. Sorry if was not crystal clear about this.
All what your language can do inline is OK. So if a functional language has a strange syntax that resembles a function call but is inlined, that's OK.
Shortest code wins.

As a side note: this challenge is related to a quasi-real problem: a fast scoring function in mastermind game.

Would you allow basic list operations in functional languages (like map and fold)? At minimum, you can create all of the other common operations from fold.

Also what about recursion and pattern matching?

@Jwosty Recursion involves function call (I think). I'm not fluent in functional languages, but I can't forbid basic list operation in (for instance) lisp.

Well, you could forbid list operations since they are functions, but I was thinking that for functional languages you could put it on par with +. Also, in some functional languages, tail recursion is optimized away to what is equivalent to a for loop, so I might allow tail recursion (but not just any recursion).

That's the second question I've seen recently which talks about comparison operators being compiled to if statements. What weird architecture does this?

@Peter the wording is the same because it's a copy/paste from http://codegolf.stackexchange.com/questions/32081/calculate-n-12. But than ternary ?: IS compiled to a branch, so are the lazy && and ||. Even comparisons may be compiled to branching code.

Also, how do you expect us to iterate the array without branching? The code will have to know when to stop at some point...

C/C++ with SSE intrinsics (11 instructions)
Because everything's better with SIMD...
inline int foo(const int16_t *a, const int16_t *b)
{
    __m128i va = _mm_loadu_si128((__m128i *)a);
    __m128i vb = _mm_loadu_si128((__m128i *)b);
    __m128i vmin = _mm_min_epi16(va, vb);
    vmin = _mm_add_epi32(_mm_unpacklo_epi16(vmin, vmin), _mm_unpackhi_epi16(vmin, vmin));
    vmin = _mm_add_epi32(vmin, _mm_srli_si128(vmin, 4));
    vmin = _mm_add_epi32(vmin, _mm_srli_si128(vmin, 8));
    return _mm_cvtsi128_si32(vmin);
}

No branches, loops or function calls. This might not be the shortest source code, but it compiles to just 11 SSE instructions, so I claim shortest generated code.

I really like it, but can't find any reference to _mm_loadu_epi16 (https://software.intel.com/sites/landingpage/IntrinsicsGuide/)

Sorry - I used one of my personal convenience macros without thinking - it's really just _mm_loadu_si128. I've updated the answer.

vb.net
v = a.Zip(b,Function(p,q) Math.Min(p,q)).Sum
v = a.Zip(b,AddressOf Math.Min).Sum

Edit:
 A no function call version. Just a single expression.
Dim v = {a(0), a(0), b(0)}(1 + ((a(0) - b(0)) / ((a(0) - b(0)) * (a(0) - b(0)) ^ (1 / 2)))) +
        {a(1), a(1), b(1)}(1 + ((a(1) - b(1)) / ((a(1) - b(1)) * (a(1) - b(1)) ^ (1 / 2)))) +
        {a(2), a(2), b(2)}(1 + ((a(2) - b(2)) / ((a(2) - b(2)) * (a(2) - b(2)) ^ (1 / 2)))) +
        {a(3), a(3), b(3)}(1 + ((a(3) - b(3)) / ((a(3) - b(3)) * (a(3) - b(3)) ^ (1 / 2)))) +
        {a(4), a(4), b(4)}(1 + ((a(4) - b(4)) / ((a(4) - b(4)) * (a(4) - b(4)) ^ (1 / 2)))) +
        {a(5), a(5), b(5)}(1 + ((a(5) - b(5)) / ((a(5) - b(5)) * (a(5) - b(5)) ^ (1 / 2)))) +
        {a(6), a(6), b(6)}(1 + ((a(6) - b(6)) / ((a(6) - b(6)) * (a(6) - b(6)) ^ (1 / 2)))) +
        {a(7), a(7), b(7)}(1 + ((a(7) - b(7)) / ((a(7) - b(7)) * (a(7) - b(7)) ^ (1 / 2))))

Note: Above fails in a(x)=b(x) as a(x)-b(x) = 0 which results in divide by zero .
((a(0) - b(0)) / ((a(0) - b(0)) * (a(0) - b(0)) ^ (1 / 2)))
 delta = a(x)-b(x)
   abs = (delta * delta)^(1/2)  ; Sqr(delta^2)
  sign = delta / abs            ; This is where the 0/0 happens.
 index = sign + 1               ; Since sign in normalise to -1 to +1
                                ; when need offset it by +1 for 0-Indexed arrays.

Version using < in mathematical sense. (akin to @Heiko Oberdiek entry)
Dim v = {a(0),b(0)}((a(0)<b(0))+1)+{a(1),b(1)}((a(1)<b(1))+1)+{a(2),b(2)}((a(2)<b(2))+1)+{a(3),b(3)}((a(3)<b(3))+1)+
        {a(4),b(4)}((a(4)<b(4))+1)+{a(5),b(5)}((a(5)<b(5))+1)+{a(6),b(6)}((a(6)<b(6))+1)+{a(7),b(7)}((a(7)<b(7))+1)

I see Zip and Min as function calls, dont'you?

min is a function call also.

yes the core of the challenge is avoid it.

+1 Not fast but clever. Is this {} a recent addition to VB?

It has had someingthing akin to them since at least VS2005 release (VB8?)
VB also has another alternative CHOOSE( ).

What is needed is a way to calculate Math.Sign without any division.

APL, 7 (should be invalid)
v←+/a⌊b

a⌊b is the minimum of each corresponding pair of items.
+/ adds everything together in the last dimension, which is the only dimension in this case.
Thanks to Adam Speight who pointed out that these symbols are called "functions" in APL. So this answer should be invalid and not fixable...

Please use some of that 30 chars for an explanation...

@user23013 Aren't you also using Dyadic functions

@AdamSpeight You are right...

But I doubt what will happen if someone say methods are not called functions in some languages.

Not using functions in a functional language is quite hard.

JavaScript - 84 89 97 98
The code:
for(s=i=7;i--;s+=x*r/r|0+y*l/l|0){x=~-a[i];y=~-b[i];l=0xff&1<<(x-y);r=0xff&1<<(y-x)}

49 if the comparison operators are allowed in numerical context:
for(s=i=7;i--;s+=(x=~-a[i])-(x-y)*(y<x))y=~-b[i];

The input is in the a and b arrays. The result is stored in the s variable.
Ungolfed version:
for(s = i = 7; i--; s += x*r/r|0 + y*l/l|0, --s) {
    // Get the last elements of the arrays
    x = a[i];
    y = b[i];

    // Calculate which is greater
    l = 0xff & 1 << (x - y);
    r = 0xff & 1 << (y - x)
}

Sample usage:
> a=[1,4,3];b=[2,3,5];
[ 2, 3, 5 ]
> for(s=i=7;i--;s+=x*r/r|0+y*l/l|0,--s){x=a[i];y=b[i];l=0xff&1<<(x-y);r=0xff&1<<(y-x)}
4
> s
7

I like the count down with the offset in the sum.
As is, the short code is broken. But with little effort you can modify it to score no more than 47 with just shift, +, - .

@edc65 It's working now, but I can't make it less than 49 bytes :(

Perl, 52 bytes
$v+=(($A=$a[$_])<=($==$b[$_]))*$A+($A>$=)*$=for 0..7

It is a single line expression without functions and if statements.
In an updated question, loops are excluded because of the end condition. In this case the for operator unfolds an array. It is not clear, whether this is acceptable or not, thus it is something for the OP to decide.
(Of course, for could be avoided by making the summation explicit, but such a solution would be too boring for me).
The input numbers are expected in arrays @a and @b. The sum is stored in $v. (If it is used a second time, $v needs to be reset to zero.)
The minimum summand for each value in the index array 0..7 is calculated and added to the result variable $v. As far as I have understood the question, the for operator is not excluded.
The result of the comparison operators <= and > are not used inside an if condition, but in a numerical context.
Ungolfed with test:
@a = (1,7,3,4,5,0,3);
@b = (3,1,4,1,5,2,6);
$v = 0;

for $_ (0..7) {
    $A = $a[$_];
    $B = $b[$_];
    $v += ($A <= $B) * $A
        + ($A > $B) * $B
}
# The use of $= instead of $B in the golfed version saves one byte.

print  "Result: $v\n";

Result: 14

The for is OK for me, I tried to clarify again.

C, 81 68
Not the shortest, but I found this interesting, so here's mine. Thanks to @edc65 for the improvement, which is not only shorter, but also faster.
int s,i;for(s=i=0;i<7;s+=(((x[i]-y[i])>>31)&(x[i]-y[i]))+y[i],i++);

Just &, shift, multiplication and addition, no division. Replace 0x80000000 and 31 with the appropriate constants for non-4-bytes ints. Loop can be unrolled (and gcc with -O3 unrolls it for me.) Usage:
int main(void) {
  signed int x[7] = {1,2,3,4,5,6,7};
  signed int y[7] = {9,0,5,7,1,2,7};
  int s,i;
  for (s=0,i=0;i!=7;s+=(((x[i]-y[i])&0x80000000)>>31)*(x[i]-y[i])+y[i],i++);
  return s;
}

produces
gcc min_bare.c && ./a.out ; echo $?
18

Let's compare with the forked if version (b)
if x[i] > y[i]
  s+=y[i]
else
  s+=x[i]
end

and with (c)
s+= ((x[i] > y[i]) ? y[i] : x[i]);

Let's benchmark with (taking the arrays from stdin)
int main(void) {
  int l,i,j,s;
  scanf("%d",&l);
  signed int x[l], y[l];
  for (i=0; i!=l; scanf("%d",&(x[i++])));
  for (i=0; i!=l; scanf("%d",&(y[i++])));
  for (j=0; j!=99999999;j++) {
    for (s=0,i=0;i!=l;i++) {
      // put code to test here
    }
  }
  printf("%d\n",s);
  return 0;
}

The if version (b) takes ~4.3s, version (c) ~3.4s, the original ~5.3s ~4.3s; all with -O3. So don't optimize prematurely ; )

Nice answer. Fiddling with it I found this one, that is shorter and faster (avoidig multiply): s += ( ( (x[i]-y[i]) >>8 ) & (x[i]-y[i]) ) + y[i]; (shift more, up to 31, for bigger numbers)

Nice find. Runtime-wise, this puts it on par with the if-version. And I learned something new. I had the wrong idea about the binary representation of signed ints, or rather the definition of the shift operator - it will preserve the sign bit. Took me a bit to figure out why your improvement works ; )

Perl, 42
$s+=($a[$_],$b[$_])[$b[$_]<$a[$_]]for 0..7

I expect scripting/C-like languages with sigil-free syntax will fare slightly better in terms of their code-golf scores. Loops over the indices and creates a list with the element from @a and @b. The index is determined by the result of the < comparison.
Just for kicks, one could write the following to make the logic scale for any number of elements by selecting the upper limit for the index variable to be the larger of $#a or $#b:
$s+=($a[$_],$b[$_])[$b[$_]<$a[$_]]for 0..($#a,$#b)[@a<@b]

J (9)
v=:+/a<.b

Someone is going to need to help me out on this one. Does this match the rules?
Single line expression

Check.
No function calls or method calls (except for basic operations like sum, if your language mandate this)

The things J is made of are called verbs (it is basically impossible to write any J without verbs), are those considered functions?
No if statements, including things that compile to if statements such as ternary operators or "greater than" operators

<. is basically equal to min, and +/ is basically equal to sum. Are those considered to compile to if statements?

While I don't want limit the challenge to imperative languages, it's difficult to apply the rules to functional languages. The problem here is the verb(s) <. that maps to either an inlined if a < b then a else b or to a library function that do the same.

@edc65 it's more like Python's [min(c,d) for c,d in zip(a,b)]. One could argue that min = lambda a,b: a if a < b else b, and that it also should be excluded, but that's also used in other answers. TL;DR: I'm not sure.

Golfscript, 13
0\~zip{$0=+}/

The arguments have to be passed to the program as a list of the two lists (e.g. [ [0 1 2] [4 2 0] ]).
I'm really not sure if it matches the rules, though (you said you won't forbid basic list operations? - zip in this case).
Explanation:

Golfscript pushes the arguments it get as a string into the stack before the program runs.
0\ pushes 0 and switching top elements of the stack (will be used for the sum).
~ executes the code in the string, which is just pushing the array down the stack.
zip transposes array's rows with columns (e.g. [[0 1 2][4 2 0]] -> [[0 4][1 2][2 0]]).
{...}/ executes a block ({...}) over each element of the array.
$0=+ sorts each array in the big array gets the first element and adds to the "sum".

At the end of the program only the sum is left on stack and the stack values are printed.

Can you add some explanation? I'm not fluent in Golfscript.


text:
Apply English punctuation rules
You've been hired to write some code for a dictation-taking app, which takes voice input from a spoken source, parses it as words, and writes it down on a screen.
The management doesn't really trust you with all that much powerin the project—you're known to sit around and golf code all day instead of doing your work, unfortunately—so they just give you a really simple task to perform: turn a Sentence with interspersed Punctuation into a properly formatted sentence, where 'properly formatted' is defined below.

The Sentence is the string of input. A Word is a group of continguous non-space characters. A Punctuation is a Word whose first character is ^.
A Word is capitalized if the first letter of the Word is not a lowercase letter (capitalized words match the regex /[^a-z].*/).
The first Word of the Sentence must be capitalized.
A ^COMMA is the comma character , and has a space following but not preceding. aaa ^COMMA bbb becomes aaa, bbb.
A ^COLON is a comma that looks like :.
A ^SEMICOLON is a comma that looks like ;.
A ^PERIOD is a comma that looks like .. The word following a ^PERIOD must be capitalized.
A ^BANG is a period that looks like !.
A ^DASH is the dash character - and has a space both preceding and following.
A ^HYPHEN is also the dash character - but has no space following or preceding.
An ^EMDASH is a hyphen (not a dash!) that is spelled --.
An ^OPENQUOTE is a quote character " that has a space preceding but not following. The word following an ^OPENQUOTE must be capitalized. If an ^OPENQUOTE is preceded by a Word that is not Punctuation, add a ^COMMA between that word and the ^OPENQUOTE. If an ^OPENQUOTE is preceded by a Punctuation that makes the next word capitalized, this skips over the ^OPENQUOTE to the next word.
A ^CLOSEQUOTE is the digraph ," that has a space following but not preceding. If a ^CLOSEQUOTE is preceded by a ^COMMA, ^PERIOD, or ^BANG, that Punctuation disappears and the ^CLOSEQUOTE is spelled ,", .", or !" respectively. If the disappearing Punctuation specified a capitalization, that capitalization must still occur on the next available word.
Initial or trailing spaces in the full final result must be removed, and any string of two or more spaces in a row must be all collapsed into a single space character.
Any case not covered above (e.g. ^COMMA ^COMMA or ^SEMICOLON ^CLOSEQUOTE or ^UNDEFINEDPUNCTUATION) will not occur in well-formed input and is thus undefined behaviour.

The development team informs you of the following:

The project is being written in the language [your language here], and should be as short as possible so that it takes up as little space as possible when it's an app for Android/iPhone. You try to explain that that's not how app development works, but they don't listen. But hey, what a coincidence! You're an amazing golfer in [your language here]!
The app will not have any web access permissions, and there won't be any libraries installed that do this formatting for you. You can probably convince the team lead to allow you a regex library if one exists for your language, though, if you think you need one.
Support for nested quotations that use double/single quotes properly is planned for a later version of the app, but not the version that you're working on now, so don't worry about it.
The management is a huge fan of test-driven development, and so the dev team has already had some hapless keyboard monkey write up some tests for your portion of the program: (newlines added for readability, treat them as spaces)
Input:
hello ^COMMA   world ^BANG

Output:
Hello, world!

Input:
once upon a time ^COMMA there was a horse ^PERIOD that horse cost me $50
^PERIOD ^OPENQUOTE eat your stupid oats ^COMMA already ^BANG ^CLOSEQUOTE
I told the horse ^PERIOD the horse neighed back ^OPENQUOTE no ^CLOSEQUOTE
and died ^PERIOD THE END

Output:
Once upon a time, there was a horse. That horse cost me $50. "Eat your
stupid oats, already!" I told the horse. The horse neighed back, "No,"
and died. THE END

Input:
begin a ^PERIOD b ^COMMA c ^COLON d ^SEMICOLON e ^BANG f ^HYPHEN g ^DASH h
^EMDASH i ^OPENQUOTE j ^PERIOD ^OPENQUOTE k ^SEMICOLON ^OPENQUOTE l
^CLOSEQUOTE m ^BANG ^CLOSEQUOTE n ^PERIOD 0x6C6F6C end

Output:
Begin a. B, c: d; e! F-g - h--i, "j. "K; "l," m!" N. 0x6C6F6C end

This is a code golf: the lowest score wins. You may write a function of one string argument, or a program reading from STDIN and writing to STDOUT.

What if I want to use javascript? There is no standard input in it. Can I use prompt()?

@nicael OP mentions using one string argument, so for my JS example I just made a function that takes one argument and assumed that argument was the string of words similar to STDIN

I wonder if there is esolang named "[your language here]"

JavaScript: 653 611 547 514 487 bytes
Oh my gosh. Brendan Eich I'm so sorry for this.
PS: I've added white space for readability, but stripping all allowable white space results in the byte count listed.
Theoretically I could shorten some parts like the -e- to something like -e or -e, but that might cause an issue if the previous word ends with, or the following word begins with the letter 'e' (or whichever word I decide to use). I suppose I could use an ASCII character. I'll look into that.
487 FF22+ Only
R = "replace", C = "charAt", U = "toUpperCase";
alert(a[R](/\^((COMMA)|(SEMICOLON)|(COLON)|(PERIOD)|(BANG)|(DASH)|(HYPHEN)|(EMDASH)|(OPENQUOTE)|(CLOSEQUOTE))/g, ((m, _, a, b, c, d, e, f, g, h, i, j) => a ? "," : b ? ";" : c ? ":" : d ? "." : e ? "!" : f ? "-" : g ? "-h-" : h ? "-e-" : i ? ' "' : '" '))[R](/\s((\.)|(\!)|(\,)|(\;)|(\:)|(\-\h\-\s)|(\-\e\-\s))/g, ((k, l, v, n, o, p, q, r, s) => v ? "." : n ? "!" : o ? "," : p ? ";" : q ? ":" : r ? "-" : "--"))[R](/[^!,"'.]\"\s/g, '"')[R](/.+?[\.\?\!](\s|$)/g, (t => t[C](0)[U]() + t.substr(1)))[R](/\"[a-z]/g, (u => u[C](0) + u[C](1)[U]())))

514 FF22+ Only
alert(function(z) {
    R = "replace", C = "charAt", U = "toUpperCase";
    return z[R](/\^((COMMA)|(SEMICOLON)|(COLON)|(PERIOD)|(BANG)|(DASH)|(HYPHEN)|(EMDASH)|(OPENQUOTE)|(CLOSEQUOTE))/g, ((m, _, a, b, c, d, e, f, g, h, i, j) => a ? "," : b ? ";" : c ? ":" : d ? "." : e ? "!" : f ? "-" : g ? "-h-" : h ? "-e-" : i ? ' "' : '" '))[R](/\s+((\.)|(\!)|(\,)|(\;)|(\:)|(\-\h\-\s+)|(\-\e\-\s+))/g, ((k, l, v, n, o, p, q, r, s) => v ? "." : n ? "!" : o ? "," : p ? ";" : q ? ":" : r ? "-" : "--"))[R](/[^!,"'.]\"\s/g, '"')[R](/.+?[\.\?\!](\s+|$)/g, (t => t[C](0)[U]() + t.substr(1)))[R](/\"[a-z]/g, (u => u[C](0) + u[C](1)[U]()))
}(a))

547 FF22+ Only
alert(function(z) {
    R = "replace", C = "charAt", U = "toUpperCase";
    return z[R](/\^((COMMA)|(SEMICOLON)|(COLON)|(PERIOD)|(BANG)|(DASH)|(HYPHEN)|(EMDASH)|(OPENQUOTE)|(CLOSEQUOTE))/g, ((m, _, a, b, c, d, e, f, g, h, i, j) => a ? "," : b ? ";" : c ? ":" : d ? "." : e ? "!" : f ? "-" : g ? "-h-" : h ? "-e-" : i ? ' "' : '" '))[R](/\s+((\.)|(\!)|(\,)|(\;)|(\:)|(\-\h\-\s+)|(\-\e\-\s+))/g, ((xx, __, k, l, m, n, o, p, q) => k ? "." : l ? "!" : m ? "," : n ? ";" : o ? ":" : p ? "-" : "--"))[R](/[^!,"'.]\"\s/g, '"')[R](/.+?[\.\?\!](\s+|$)/g, function(r) {
        return r[C](0)[U]() + r.substr(1)
    })[R](/\"[a-z]/g, function(s) {
        return s[C](0) + s[C](1)[U]()
    })
}(a))

611 FF 22+ Only
alert(function(c) {
    return c.replace(/\^((COMMA)|(SEMICOLON)|(COLON)|(PERIOD)|(BANG)|(DASH)|(HYPHEN)|(EMDASH)|(OPENQUOTE)|(CLOSEQUOTE))/g, ((x, _, a, b, c, d, e, f, g, h, i) = > a ? "," : b ? ";" : c ? ":" : d ? "." : e ? "!" : f ? "-" : g ? "-h-" : h ? "-e-" : i ? ' "' : '" ')).replace(/\s+\./g, ".").replace(/\s+\!/g, "!").replace(/\s+\,/g, ",").replace(/\s+\;/g, ";").replace(/\s+\:/g, ":").replace(/\s\-\h\-\s/g, "-").replace(/[^!,"'.]\"\s/g, '"').replace(/\s+\-\e-\s+/g, "--").replace(/.+?[\.\?\!](\s+|$)/g, function(b) {
        return b.charAt(0).toUpperCase() + b.substr(1)
    }).replace(/\"[a-z]/g, function(b) {
        return b.charAt(0) + b.charAt(1).toUpperCase()
    })
}(a))

653 cross-browser
alert(function(c) {
    return c.replace(/\^COMMA/g, ",").replace(/\^SEMICOLON/g, ";").replace(/\^COLON/g, ":").replace(/\^PERIOD/g, ".").replace(/\^BANG/g, "!").replace(/\^DASH/g, "-").replace(/\^HYPHEN/g, "h-h").replace(/\^EMDASH/g, "-e-").replace(/\^OPENQUOTE/g, ' "').replace(/\^CLOSEQUOTE/g, '" ').replace(/\s+\./g, ".").replace(/\s+\!/g, "!").replace(/\s+\,/g, ",").replace(/\s+\;/g, ";").replace(/\s+\:/g, ":").replace(/\s\h\-\h\s/g, "-").replace(/[^!,"'.]\"\s/g, '"').replace(/\s+\-\e-\s+/g, "--").replace(/.+?[\.\?\!](\s|$)/g, function(b) {
        return b.charAt(0).toUpperCase() + b.substr(1)
    }).replace(/\"[a-z]/g, function(b) {
        return b.charAt(0) + b.charAt(1).toUpperCase()
    })
}(a))

How it works:

 https://gist.github.com/ericlagergren/1a61b5d772ae49ab3aea

JSFiddle (for the 653 byte cross-browser solution)
JSFiddle (for the 595 FF 22+ only solution)
JSFiddle (for the 547 FF 22+ only solution)
JSFiddle (for the 514 FF 22+ only solution)
JSFiddle (for the 487 FF 22+ only solution)
This is the first time I've had to write JS that uses more than one regex, and usually my regex is predefined.
I'll continue to shave off bytes as much as I can.

You can shorten your first replaces like this: c.replace(/\^((COMMA)|(SEMICOLON)|(COLON)|(PERIOD)|(BANG))/g,(m,_,a,b,c,d,e)=>a?',':b?';':c?':':d?'.':'!')) ... and so on. Arrow sintax is short, but even 'function' should save same chars

You're right. I tested my regexp with Chrome, and it doesn't support fat arrows. I'm working on getting it straightened out with FF right now, but I hate how regexps don't really have an "and" operator like they do an "or". @edc65

@edc65 so I figure I'll have to use two =>s in order to get it to work, but using the arrows saved me 40 bytes!

Replace replace with R='replace' ... [R] ;-)

Just did that :) Got it down to 563 @edc65

Oh, and by keeping all my variables within the a-z alphabet I got it to 549 :D

Pushing the FF peculiarity, you can still drop some 'function'. Then, if you have just expressions, cut the {} block and the 'return'. IE {a;b;return d} ==> (a,b,d) Then ... maybe nothing else

@edc65 you mean changing the second two functions to fat arrows..?

Let us continue this discussion in chat.

PHP, 412 bytes
(Ungolfed here for clarity; see ideone for golfed version.)
PHP's preg_replace() function will accept array arguments, which is pretty useful here. I think the following code does everything that's required. It passes all the test cases at least.
function x($s) {
    $r='preg_replace';
    $s=$r('/ +/',' ',$s);
    $s=$r(array('/ \^COMMA/','/ \^COLON/','/ \^SEMICOLON/','/ \^PERIOD/','/ \^BANG/',
                '/\^DASH/','/ \^HYPHEN /','/ \^EMDASH /','/\^OPENQUOTE /','/ \^CLOSEQUOTE/'),
          array(',',':',';','.','!','-','-','--','"',',"'),
          $s);
    $s=$r('/(^\W*\w|([\.!]| ")\W+\w)/e','strtoupper("$0")',$s);
    $s=$r('/([,\.!]),/','\1',$s);
    $s=$r('/(\w)( "\w)/e','"$1,".strtoupper("$2")',$s);
    echo $s;
}

Works perfectly! http://ideone.com/AYtTiI Although what I'm confused about is are we supposed to have commas before open quotes? Because, grammatically speaking, quotation marks are for more than speech, yet only speech has the comma before the quotes. I assumed since there was a ^COMMA we'd be letting the user input the comma

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Function/macro that returns true if one of its arguments contains a call to itself
Write a function (or macro) that returns true if and only if at least one of its arguments contains a call to the function itself and false otherwise.
For example:
int a=function(); //a==false
int b=function(0); //b==false
int c=function(function(0)); //c==true
int d=function(3*function(1)+2); //d==true (weakly-typed language)
bool e=function(true||function(1)); //e==true (strongly-typed language)
EDIT: The function/macro may call other auxiliary function/macros.
EDIT 2: The function must take at least one argument, unless the language used behaves like C, where a function that takes no arguments may still be called with arguments nonetheless.

Does it have to work in a context like print(func(), func(func())), or will there only ever be a top-level call to the function right after it has been defined?

It should work in that situation.

Why accept so quickly?

Do I get to choose the number of arguments? If so, I assume >= 1 arguments (otherwise we could do boolean function(){return false;})

In C, you can pass arguments to functions that take 0 arguments, unless they were declared as return_type function(void);.If the language you're using does not allow that, then it needs to take 1 or more arguments.

A question about your 4th example: in strongly-typed languages, assuming function returns boolean, you cannot compile 3*function(1)+2. So can I assume in such languages the example can be true||function(1)?

The function must return false elsewise or just anything else?

@Jacob: That's correct, I edited the question to clarify that

@WilliamBarbosa the function must return false otherwise

I dislike this question because it's only solvable in languages that allow you to examine the expression tree at runtime.

@FUZxxl: I disagree; I've just posted an answer which works just fine even if the calls go indirectly through an FFI (and thus the expression tree of the interior functions can't be viewed).

Mathematica...
...was made for this.
SetAttributes[f, HoldAll]
f[x___] := ! FreeQ[Hold@x, _f]

f[]             (* False *)
f[0]            (* False *)
f[f[0]]         (* True *)
f[3 f[1] + 2]   (* True *)
f[True || f[1]] (* True *)

Everything is an expression, and an expression has a Head and a number of elements. So 1+2 is actually Plus[1,2], and {1,2} is actually List[1,2]. This means we can match any expression for the head we're interested in - in this case the function f itself.
All we need to do is find a way to prevent Mathematica from evaluating the function arguments before the function is called, such that we can analyse the expression tree within the function. What's what Hold and HoldAll is for. Mathematica itself uses this to all over the place to provide special cases for certain implementations. E.g. if you call Length[Permutations[list]] it will never actually create all those permutations and waste loads of memory, but instead realise that it can simply compute this as Length[list]!.
Let's look at the code above in detail, using the last call f[True || f[1]] as an example. Normally, Mathematica will evaluate function arguments first, so this would simply short-circuit and call f[True]. However we have set
SetAttributes[f, HoldAll]

This instructs Mathematica not to evaluate the arguments, so the FullForm of the call (i.e. the internal expression tree, without any syntactic sugar) is
f[Or[True,f[1]]]

And the argument will actually be received by f in this form. The next issue is that, within f, as soon as we use the argument, Mathematica will again try to evaluate it. We can suppress this locally with Hold@x (syntactic sugar for Hold[x]). At this point we've got a handle on the original expression tree and do with it whatever we want.
To look for a pattern in an expression tree we can use FreeQ. It checks that a given pattern is not found in the expression tree. We use the patter _f, which matches any subexpression with head f (exactly what we're looking for). Of course, FreeQ returns the opposite of what we want, so we negate the result.
One more subtlety: I've specified the argument as x___, which is a sequence of 0 or more elements. This ensures that f works with any number of arguments. In the first call, f[] this means that Hold@x will simply become Hold[]. If there were multiple arguments, like f[0,f[1]], then Hold@x would be Hold[0,f[1]].
That's really all there is to it.

C++11
Similar to expression templates we can propagate the fact that we did call the function inside a functions parameters list in its return type.
At first we need some helper classes and functions:
#include <iostream>

template <bool FunctionWasInParameters> struct FunctionMarker {
  operator bool() const { return FunctionWasInParameters; }

  operator int() const { return FunctionWasInParameters; }
};

template <bool... values> struct Or;

template <bool first, bool... values> struct Or<first, values...> {
  static constexpr bool value = first || Or<values...>::value;
};

template <> struct Or<> { static constexpr bool value = false; };

template <class T> struct is_FunctionMarker {
  static constexpr bool value = false;
};

template <bool B> struct is_FunctionMarker<FunctionMarker<B>> {
  static constexpr bool value = true;
};

#define OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(OPERATOR)                        \
  template <bool B, class T>                                                   \
  FunctionMarker<B> operator OPERATOR(FunctionMarker<B>, T) {                  \
    return {};                                                                 \
  }                                                                            \
  template <bool B, class T>                                                   \
  FunctionMarker<B> operator OPERATOR(T, FunctionMarker<B>) {                  \
    return {};                                                                 \
  }                                                                            \
  /* to break ambiguity by specialization */                                   \
  template <bool B, bool B2>                                                   \
  FunctionMarker<B || B2> operator OPERATOR(FunctionMarker<B>,                 \
                                            FunctionMarker<B2>) {              \
    return {};                                                                 \
  }

OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(|| )
OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(+)
OVERLOAD_OPERATOR_FOR_FUNCTION_MARKER(*)
// TODO: overload all other operators!

Now, we can use it for the exact same code as in the question:
template <class... Args>
auto function(Args... args)
    -> FunctionMarker<Or<is_FunctionMarker<Args>::value...>::value> {
  return {};
}

FunctionMarker<false> function() { return {}; }

int main() {
  int a = function();
  int b = function(0);
  int c = function(function(0));
  int d = function(3 * function(1) + 2);
  bool e = function(true || function(1));

  // clang-format off
  std::cout << a << "//a==false\n"
            << b << "//b==false\n"
            << c << "//c==true\n"
            << d << "//d==true (weakly-typed language)\n"
            << e << "//e==true (strongly-typed language)\n";
}

Output from ideone:
0//a==false
0//b==false
1//c==true
1//d==true (weakly-typed language)
1//e==true (strongly-typed language)

C#
public PcgBool f(params object[] args)
{
    return args.Any(p => p is PcgBool);
}

public class PcgBool
{
    public PcgBool() { }
    public PcgBool(bool value)
    {
        Value = value;
    }

    private bool Value;

    public static implicit operator bool(PcgBool pcgBool)
    {
        return pcgBool.Value;
    }

    public static implicit operator PcgBool(bool value)
    {
        return new PcgBool(value);
    }
}

Usage (in LINQPad):
void Main()
{
    Console.WriteLine(f(1,2,f(3),4)); // True
    Console.WriteLine(f(1,2,3,"4")); // False
}

The trick here is to make f more aware of the parameters, by passing a custom type (PcgBool) which is kind-of-like a boolean.
P.S. I hope returning a custom type which is implicitly castable from and to a bool is not considered as cheating. Technically you can use the return value as if it was of bool type, and the question asked to "return true if and only if" etc., but never stated the return type must be bool.

What about f(new PcgBool())?

Hmm... You are right about that one. It does look like it brakes my answer. Unfortunately, I'm too lazy to fix it by now (it's been a while...)

Lua
local x
local function f()
    local y = x
    x = true
    return y
end
debug.sethook(function()
        if debug.getinfo(2).func ~= f then
            x = false
        end
    end, "l")
print(f())
print(f(0))
print(f(f()))
print(f(f(0)))
print(f("derp" .. tostring(f())))

And I was thinking of a way to compare tables recursively. Well done, I didn't think debug could be that powerful!

C++11 TMP
This one is a bit longer. Because of some limitations in C++ templates I had to do everything with types. Thus "True" as well as the numbers were turned into bool and int. Also The operations +, - and || were turned into add, mul and or_.
I hope this still qualifies as a valid answer.
template <typename... Args>
struct foo;

template <>
struct foo<>
{
    static bool const value = false;
};

template <typename T>
struct is_foo
{
    static bool const value = false;
};

template <typename... Args>
struct is_foo<foo<Args...>>
{
    static bool const value = true;
};

template <typename T>
struct is_given_foo
{
    static bool const value = false;
};

template <template <typename...> class T, typename... Args>
struct is_given_foo<T<Args...>>
{
    static bool const value = foo<Args...>::value;
};

template <typename Head, typename... Tail>
struct foo<Head, Tail...>
{
    static bool const value = is_foo<Head>::value || is_given_foo<Head>::value || foo<Tail...>::value;
};

template <typename... Args>
struct add {};

template <typename... Args>
struct mul {};

template <typename... Args>
struct or_ {};

static_assert(foo<>::value == false, "int a=function(); //a==false");
static_assert(foo<int>::value == false, "int b=function(0); //b==false");
static_assert(foo<foo<int>>::value == true, "int c=function(function(0)); //c==true");
static_assert(foo<add<mul<int, foo<int>>, int>>::value == true, "int d=function(3*function(1)+2); //d==true (weakly-typed language)");
static_assert(foo<or_<bool,foo<int>>>::value == true, "bool e=function(true||function(1)); //e==true (strongly-typed language)");

// just for the sake of C++
int main()
{
    return 0;
}

Really nice! What rule causes the second definition of is_given_foo to be preferred to the first one?

Maybe some one can help me, because I was not able to find the right place in the standard to cite. Anyway as the second is_given_foo is a template specialization of the first one it is always preferred when the template parameter(s) match the given pattern, in that case when the parameter is a template itself.

C
I don't think it can be done with procedures, but we can always (ab)use macros.
#include <stdio.h>
#define f(x) ((max_depth = ++depth), (x), (depth-- < max_depth))

int depth = 0;
int max_depth = 0;

char* bool(int x) { // Helper - not necessary for solution
  return x ? "true" : "false";
}

int main() {
  printf("f(1): %s\n", bool(f(1)));
  printf("f(f(1)): %s\n", bool(f(f(1))));
  printf("f(bool(f(1))): %s\n", bool(f(bool(f(1)))));
  printf("f(printf(\"f(1): %%s\\n\", bool(f(1)))): %s\n", bool(printf("f(1): %s\n", bool(f(1)))));
}

This outputs:
f(1): false
f(f(1)): true
f(bool(f(1))): true
f(1): false
f(printf("f(1): %s\n", bool(f(1)))): true

Our macro f keeps track of the current depth, and the maximum depth achieved since it was invoked. If the latter is greater than the former, then it has been called recursively.

Heh. We ended up with more or less the same solution at more or less the same time.

@Art LOL. Also, I feel very silly now, as I wasn't aware of the comma operator (since C's somewhere around my 4th or 5th choice language), which I hacked around using && and ||. I may try to redeem my answer.

Well, the comma operator is just for an extra layer of obfuscation. I'd never use it in normal code. But in this case I confused myself when trying to use logical operators.

C, 13
#define F(X)0

The argument is never expanded, so it cannot call any macros. It is nothing more than a bunch of plain text. Thus, the answer is always false.

This is really a brilliant answer.

Came across this while looking at old preprocessor posts... actually, this is wrong.  F(F(0)) will happily first evaluate F's argument, F(0).  That argument expands to 0.  Then it evaluates F without blue paint on its argument of 0, resulting in 0.  The non-recursive restriction does not apply; that's when e.g. I have #define F(X) G and #define G F(Y) is in play; in this case, while expanding F(0) to G, and then to F(Y), the token F appears.  Because I'm currently expanding F, F has blue paint in this case, and thus the expansion stops at F(Y).

@HWalters Wow, you're right. What do you think of my new explanation?

So it sounds like now you're saying that since X isn't in the argument replacement list, whatever macros were bound to it are never expanded.  If we interpret that as a function being called, that means the argument's functions are never called.  Yes, I think that's correct.

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BLAH(x) (strncmp( "BLAH(", #x, strlen("BLAH(")) == 0)

int main(int argc, char** argv)
{
  printf("%d\n", BLAH(1));
  printf("%d\n", BLAH("1234"));
  printf("%d\n", BLAH("BLAH"));
  printf("%d\n", BLAH(BLAHA));
  printf("%d\n", BLAH(BLAHB()));
  printf("%d\n", BLAH(BLAH));
  printf("%d\n", BLAH(BLAH()));
  printf("%d\n", BLAH(BLAH("1234")));
  return 0;
}

The macro compares if its argument starts with "BLAH(".

Doesn't work on BLAH(blub(BLAH(0))).

C
#include <stdio.h>

int a, b;
#define foo(x) (b=a++,(void)x,a--,!!b)

int
main(int argc, char **argv)
{
        printf("%d\n", foo(1));
        printf("%d\n", foo(0));
        printf("%d\n", foo(foo(1)));
        printf("%d\n", foo(foo(foo(1))));
        return 0;
}

We can count the recursion depth in the macro. We then overwrite the return value of the outer macro in the inner macro. !!b is to normalize the return value to a boolean. The preprocessed code ends up like this:
int a, b;

int
main(int argc, char **argv)
{
 printf("%d\n", (b=a++,(void)1,a--,!!b));
 printf("%d\n", (b=a++,(void)0,a--,!!b));
 printf("%d\n", (b=a++,(void)(b=a++,(void)1,a--,!!b),a--,!!b));
 printf("%d\n", (b=a++,(void)(b=a++,(void)(b=a++,(void)1,a--,!!b),a--,!!b),a--,!!b));
 return 0;
}

What about the (admittedly very silly) case of printf("%d\n", foo(printf("%d\n", foo(1)))). The inner call to foo returns 1, but doesn't call foo.

Algol 60
Here's a boolean procedure that does what the question asks for (note: Algol 60 is defined in terms of a list of tokens without fixing syntax for them, the below uses Marst syntax to represent the individual tokens that make up the program):
boolean procedure recursion detector(n);
  boolean n;
  begin
    own boolean nested, seen nested;
    boolean was nested, retval;
    was nested := nested;
    begin if nested then seen nested := true end;
    nested := true;
    retval := n; comment "for the side effects, we ignore the result";
    nested := was nested;
    retval := seen nested;
    begin if ! nested then seen nested := false end;
    recursion detector := retval
  end;

Verification
Here's the test code I used:
procedure outboolean(c, b);
  integer c;
  boolean b;
  begin
    if b then outstring(c, "true\n") else outstring(c, "false\n")
  end;

begin
  outboolean(1, recursion detector(false));
  outboolean(1, recursion detector(true));
  outboolean(1, recursion detector(recursion detector(false)));
  outboolean(1, recursion detector(false | recursion detector(true)));
  outboolean(1, recursion detector(false & recursion detector(true)));
  outboolean(1, recursion detector(recursion detector(recursion detector(false))))
end

As expected, the output is:
false
false
true
true
true             comment "because & does not short-circuit in Algol 60";
true

Explanation
Algol 60 has a different evaluation order from most languages, which has a logic of its own, and is actually much more powerful and general than the typical evaluation order, but is fairly hard for humans to get their head around (and also fairly hard for computers to implement efficiently, which is why it got changed for Algol 68). This allows for a solution with no sort of cheating (the program doesn't need to look at the parse tree or anything like that, and unlike almost all the other solutions here, this would work just fine if the nested call were made via an FFI).
I also decided to show off a few other quirks of the language. (Notably,  variable names can contain whitespace; this is fairly useful for readability, because they can't contain underscores. I also love the fact that the comment indicator is the literal word comment in most syntax encodings. Algol 68 found this fairly awkward for short comments, and introduced ¢ as an alternative. The quotes around the comment body aren't normally needed, I just add them for clarity and to prevent the comment accidentally ending when I type a semicolon.) I actually really like the broad concepts of the language (if not the details), but it's so verbose that I rarely get to use it on PPCG.
The main way in which Algol 60 differs from the languages it inspired (such as Algol 68, and indirectly C, Java, etc; people who know K&R C will probably recognise this syntax for functions) is that a function argument is treated a bit like a little lambda of its own; for example, if you give the argument 5 to a function that's just the number 5, but if you give it the argument x+1 you get exactly what you specified, the concept of "x plus 1", rather than the result of x plus 1. The difference here is that if x changes, then attempts to evaluate the function argument in question will see the new value of x. If a function argument isn't evaluated inside the function, it won't be evaluated outside the function either; likewise, if it's evaluated multiple times inside the function, it'll be evaluated separately each time (assuming that this can't be optimised out). This means that it's possible to do things like capture the functionality of, say, if or while in a function.
In this program, we're exploiting the fact that if a call to a function appears in an argument to that function, that means that the function will run recursively (because the argument is evaluated at exactly the point or points that the function evaluates it, no earlier or later, and this must necessarily be inside the function body). This reduces the problem to detecting if the function is running recursively, which is much easier; all you need is a thread-local variable that senses if there's a recursive call (plus, in this case, another one to communicate information back the other way). We can use a static variable (i.e. own) for the purpose, because Algol 60 is single-threaded. All we have to do after that is to put everything back the way it was, so that the function will function correctly if called multiple times (as required by PPCG rules).
The function doesn't return the desired value from the inside calls at the moment (at least if you assume they should look for self-calls in only their arguments, rather than counting themselves); making that work is fairly easy using the same general principles, but more complex and would obscure the workings of the function. If that's deemed necessary to comply with the question, it shouldn't be too hard to change.

Java
public class FuncOFunc{

private static int count = 0;

public static void main(String[] args){

    System.out.println("First\n" + function());
    reset();

    System.out.println("Second\n" + function(1));
    reset();

    System.out.println("Third\n" + function(function(1)));
    reset();

    System.out.println("Fourth\n" + function(3*function(1)+2));
    reset();

    System.out.println("Fifth\n" + function(function(1), function(), 4));
}

/**
 * @param args
 */
private static int function(Object...args) {
    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    count+=stackTraceElements.length;
    if(count>3) return 1;
    else return 0;
}

static void reset(){
    count = 0;
}
}

can reset() be counted as auxiliary?
Output:
First
0
Second
0
Third
1
Fourth
1
Fifth
1

EDIT
Here is another version that doesn't use the reset() method, but a lot of madness. It creates and compiles at runtime the above code with the call to the function passed as an argument in stdin. I wanted a more elegant solution but sadly I don't have too much time for this :(
To run it simply call for example javac FuncOFunc.java function(function(1),function(),4).
import java.io.File;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class FuncOFunc {
    public static void main(String[] args) throws Exception {
        JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);
        File jf = new File("FuncOFuncOFunc.java");
        PrintWriter pw = new PrintWriter(jf);
        pw.println("public class FuncOFuncOFunc{"
                + "public static void main(){ "
                + "     System.out.println("+ args[0] +");"
                + "}"
                + "     private static int function(Object...args)     {"
                + "         StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();"
                + "         if(stackTraceElements.length>3) return 1;"
                + "         else return 0;"
                + "     }"
                + "}");
    pw.close();
    Iterable<? extends JavaFileObject> fO = sjfm.getJavaFileObjects(jf);
    if(!jc.getTask(null,sjfm,null,null,null,fO).call()) {
        throw new Exception("compilation failed");
    }
    URL[] urls = new URL[]{new File("").toURI().toURL()};
    URLClassLoader ucl = new URLClassLoader(urls);
    Object o= ucl.loadClass("FuncOFuncOFunc").newInstance();
    o.getClass().getMethod("main").invoke(o);
    ucl.close();
}
}

I don't believe you can force the usage to invoke reset() after each function invocation. The idea of auxiliary functions is to allow you invoking other private methods from within function's body... But that's only my interpretation of the question, let's leave it to the asker to decide.

I have the same feeling... Let's wait for the OP to clarify this point. Meanwhile I'm working for a reset()less version. Still the code above works if there is only one call in the main (without the variable count and the reset function)

Sorry about the lack of clarity, but I meant what Jacob said by auxiliary function. Also, the 1st code you wrote will return "true" if any method, not just function(), is called inside function(...), won't it?

Your edit has to be some of the worst code I have ever seen. Have a +1.

Ahaha! Thanks! That's what happens when trying to be creative with no creativity and very little time... That's probably the worst thing I ever made in java. Still compiles though!

Python
import ast, inspect

def iscall(node, name, lineno=None):
    return isinstance(node, ast.Call) \
            and (node.lineno == lineno or lineno is None) \
            and hasattr(node.func, 'id') \
            and node.func.id == name

def find_call(node, name, lineno):
    for node in ast.walk(node):
        if iscall(node, name, lineno):
            return node

def is_call_in_args(call):
    descendants = ast.walk(call);
    name = next(descendants).func.id
    return any(map(lambda node: iscall(node, name), descendants))

def function(*args):
    this = inspect.currentframe()
    _, _, funcname, _, _ = inspect.getframeinfo(this)
    outer = inspect.getouterframes(this)[1]
    frame, filename, linenum, _, context, cindex = outer
    module = ast.parse(open(filename).read())
    call = find_call(module, funcname, linenum)
    return is_call_in_args(call)

if __name__ == '__main__':

    print("Works with these:")
    assert(function() == False)
    assert(function(3*function(1)+2) == True)
    assert(function(0) == False)
    assert(function(function(0)) == True)
    assert(function(True or function(1) == True))

    print("Does not work with multiple expressions on the same line:")
    assert(function(function()) == False); function()
    function(); assert(function(function()) == False)

Save it as selfarg.py and run it or from selfarg import function in another script. It does not work in the repl.
Using the current and outer stack frames function obtains its name and place
of call (file and line number). It then opens the obtained file and parses it
into an abstract syntax tree. It skips to the function call identified by the
line number and inspects if it has another function call with the same name in
its arguments.
edit: It's OK with python2 too. Changed python3 to python in the title.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Determine if an integer is divisible by 3
Your goal is to determine if a number is divisible by 3 without using conditionals.
The input will be an unsigned 8 bit number from 0 to 255. Creativity encouraged!
You are ONLY allowed to use

Equality/Inequality (==, !=, >, <, >=, <=)
Arithmetic (+, -, x)
Logical Operators (! not, && and, ||  or)
Bitwise Operators (~ not, & and, | or, ^ xor, <<, >>, >>> arithmetic and logical left and right shifts)
Constants (it would be better if you kept these small)
Variable assignment

Output 0 if false, 1 if true.
Standard atomic code-golf rules apply. If you have any questions please leave them in the comments. Example methods here. A token is any of the above excluding constants and variables.

@GregHewgill My typo, it should be 8 bit number.

Are we only allowed to use the above operators? Otherwise, modulo would make this way too easy.

Also, how about table lookup?

@Jwosty you are only allowed to use those, but I will take suggestions.

@GregHewgill If you use a table lookup, you have to count all tokens.

Is 0 considered to be divisible by 3?

Can you clarify what you mean by no conditionals? Is it limited to IF statements, or does it apply to things like loops as well?

@Ruslan You are only allowed to use the above.

Can I return true/false instead of 1/0?

what about Ruby's to_s or to_i? That is, toString or toInteger

C - 2 tokens
int div3(int x) {
    return x * 0xAAAAAAAB <= x;
}

Seems to work up to 231-1.
Credits to zalgo("nhahtdh") for the multiplicative inverse idea.

+1. Was baffled a bit at how the <= works, and remembered that 0xAAAAAAAB is taken to be unsigned int type, thus the result of multiplication is unsigned.

@DigitalTrauma inequality operators are allowed, not banned

@aditsu Oops! I need to read more carefully sometimes! +1 great answer!

@aditsu, sorry I'm noob, how exactly does this work?

@Kartik_Koro 0xAAAAAAAB * 3 == 1 due to overflow, so for any int x, x * 0xAAAAAAAB * 3 == x. Also y * 3 has different values for different y, therefore y = x * 0xAAAAAAAB must be the only y such that y * 3 == x. If x is a multiple of 3, then y must be x/3, otherwise it must be working through overflow. A simple way to check is to compare y with x. Also see http://en.wikipedia.org/wiki/Modular_multiplicative_inverse

@aditsu I see, +1'd thats great :D

The challenge states that the input should be unsigned. Maybe uint8_t x instead of int?

@200_success The code is compatible with the specified type and range, I see no reason to restrict it.

Python, 3 2 tokens
Brute force solution, but it works.
0x9249249249249249249249249249249249249249249249249249249249249249>>x&1

Thanks to Howard for the 1 token reduction.

Wow! Your solution is probably the shortest (3 tokens), but I want to encourage other answers too.

There is even a 2 token solution: 0x9......>>x&1.

C - 5 4 (?) tokens
int div3_m2(uint32_t n) {
    return n == 3 * (n * 0xAAAAAAABull >> 33);
}

Works for any unsigned 32-bit number.
This code makes use of multiplicative inverse modulo 232 of a divisor to convert division operation into multiplication operation.
Edit
My solution (posted 2 minutes after) has the same spirit as aditsu's solution. Credit to him for the use of == that improves my solution by 1 token.
Reference

Labor of Division - ridiculousfish.com
Hacker's Delight - Magic Number
Wikipedia - Modular multiplicative inverse

This is incredible. I knew about magic numbers from the famous inverse squareroot trick, but I didn't know it could be used for an arbitrary divisor. This is Bull :P

Yep, 0xAAAAAAAB = (2^33 + 1)/3 and 171 = (2^9 + 1)/3. I picked the smallest constant that does the trick. Hmm, actually it also seems to work with 86 = (2^8 + 2)/3

Rats, even 43 = (2^7 + 1)/3 works, not sure how I missed it. Edited now.

C - 15 (?) tokens
int div3_m1(unsigned int n) {
    n = (n & 0xf) + (n >> 4);
    n = (n & 0x3) + (n >> 2);
    n = (n & 0x3) + (n >> 2);
    return n == 0 || n == 3;
}

Since 4 ≡ 1 (mod 3), we have 4n ≡ 1 (mod 3). The digit summing rule is not limited to summing the digits, but also allows us to arbitrarily break the number into sequences of digits and sum all of them up while maintaining the congruency.
An example in base 10, divisor = 9:
1234 ≡ 12 + 34 ≡ 1 + 2 + 3 + 4 ≡ 123 + 4 ≡ 1 (mod 9)
All statements in the program makes use of this property. It can actually be simplified to a loop that runs the statement n = (n & 0x3) + (n >> 2); until n < 4, since the statement simply breaks the number in base-4 at the least significant digit and add the 2 parts up.

+1: interestingly this works for n up to 512 (actually n = 590), but I'm not quite sure why.

@PaulR: It won't work for bigger numbers due to carry (note that I used addition in the calculation). Also note the repeated lines.

Yes, I'm just not sure why it works for 9 bit values, since it only seems to be testing 8 bits?

for 9-bit numbers after the first addition it become at most 5 bits, after the first n = (n & 0x3) + (n >> 2); the result is reduced to 3 bits and the repetition caused it to remain only 2 bits http://stackoverflow.com/a/3421654/995714

oh I've made a mistake. A 5-bit number + a 4-bit number can result in a 6-bit number. But if n <= 588 adding the top 4 bits and bottom 2 bits of that 6-bit number produce an only 4-bit sum. Again adding that results in a 2-bit number. 589 and 590 results in 3 bits in the last sum but incidentally they aren't divisible by 3 so the result is correct

Python (2 tokens?)
1&66166908135609254527754848576393090201868562666080322308261476575950359794249L>>x

Or
1&0x9249249249249249249249249249249249249249249249249249249249249249L>>x

Or
1&0b1001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001>>x

Duplicate of Howard's comment

@aditsu ... Great minds think alike? I swear I didn't see that before I posted this.

JavaScript - 3 tokens
function div3(n) {
    var a = n * 0.3333333333333333;
    return (a | 0) == a;
}

This abuses the fact that using bitwise operators on a number truncates it to an integer in JavaScript.

Should be 4 tokens: =, *, |, ==

I don't think variable assignment counts as a token.

C - 4 tokens
int div3(int x) {
    return ((x * 43) >> 7) * 3 == x;
}

Works up to 383.
Previous version (bigger constants):
int div3(int x) {
    return ((x * 171) >> 9) * 3 == x;
}

Works up to 1535

Befunge 93 - 5 tokens
Fixed - division removed.
v      @._1.@
         \
         0
         +
         3
>&>3-:0\`|
  ^      <

Gets input, keeps subtracting 3 until it's smaller than 0, direct the pointer up ('|'), then adds 3. If the value is 0 then the pointer moves right ("1.@" outputs '1') else moves left ("@." outputs '0'). '@' terminates the program.

Ruby, 6(?) tokens
I'm really not sure how to count tokens.  OP, can you score me?
I think it's 6... 1, 0, 0, *, 255, x
Note that the * is not integer multiplication.
def div3(x)
  ([1,0,0]*255)[x]
end

Wouldn't a token in the OP's sense be only one of the above listed in the question?

@C5H8NNaO4 So what? 0?

@C5H8NNaO4 maybe 4 for constants?

@NotthatCharles No, one. A token is any of the above excluding constants and variables. So constants are “non-tokens” (for the purposes of scoring), but the asterisk is a token still.

Python - 25 tokens
To get things started, I have a lengthy solution that is a implementation of one of the answers in the link in my first post. n is input.
a = (n>>7)-((n&64)>>6)+((n&32)>>5)-((n&16)>>4)+((n&8)>>3)-((n&4)>>2)+((n&2)>>1)-(n&1)
print(a==0 or a==3)

or is equivalent to ||.

Tcl, 83 bytes
proc T n {while \$n>9 {set n [expr [join [split $n ""] +]]};expr {$n in {0 3 6 9}}}

Try it online!

Failed outgolf: 96 bytes proc T n {set n [expr [join [split [expr [join [split $n ""] +]] ""] +]];expr {$n in {0 3 6 9}}} Try it online!

Another fail:87 bytes proc T n {expr {[expr [join [split [expr [join [split $n ""] +]] ""] +]] in {0 3 6 9}}}
Try it online!

Pascal, 1 token
Pascal does not have bitwise operators.
(Some dialects do and some implementations use under the hood bitwise operators for operations on the set data type nevertheless.)
Since the in set membership operator is not listed among the allowed operators, another relational operator is used:
    type
        wholeNumberLessThan256 = 0..255;

    function divisibleByThree(n: wholeNumberLessThan256): Boolean;
        const
            wholeNumbersLessThan256divisibleByThree = [
                      0,   3,   6,   9,  12,  15,  18,  21,  24,  27,
                     30,  33,  36,  39,  42,  45,  48,  51,  54,  57,
                     60,  63,  66,  69,  72,  75,  78,  81,  84,  87,
                     90,  93,  96,  99, 102, 105, 108, 111, 114, 117,
                    120, 123, 126, 129, 132, 135, 138, 141, 144, 147,
                    150, 153, 156, 159, 162, 165, 168, 171, 174, 177,
                    180, 183, 186, 189, 192, 195, 198, 201, 204, 207,
                    210, 213, 216, 219, 222, 225, 228, 231, 234, 237,
                    240, 243, 246, 249, 252, 255];
        begin
            { In Pascal `<=` denotes the `⊆` operator with sets. }
            divisibleByThree := [n] <= wholeNumbersLessThan256divisibleByThree;
        end;

Extended Pascal, 0 token
NB:
A lookup table could be written in Standard Pascal (ISO standard 7185), too.
    type
        wholeNumberLessThan256 = 0‥255;

    { The reserved word `protected` is defined by Extended Pascal.
      It just means the value of `n` may not be altered in the definition. }
    function divisibleByThree(protected n: wholeNumberLessThan256): Boolean;
        type
            tableFormat = array[type of n] of Boolean;
        const
            lookupTable = tableFormat[
                      0,   3,   6,   9,  12,  15,  18,  21,  24,  27,
                     30,  33,  36,  39,  42,  45,  48,  51,  54,  57,
                     60,  63,  66,  69,  72,  75,  78,  81,  84,  87,
                     90,  93,  96,  99, 102, 105, 108, 111, 114, 117,
                    120, 123, 126, 129, 132, 135, 138, 141, 144, 147,
                    150, 153, 156, 159, 162, 165, 168, 171, 174, 177,
                    180, 183, 186, 189, 192, 195, 198, 201, 204, 207,
                    210, 213, 216, 219, 222, 225, 228, 231, 234, 237,
                    240, 243, 246, 249, 252, 255: true;
                    otherwise false
                ];
        begin
            divisibleByThree ≔ lookupTable[n];
        end;

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/