text:
Count of "a"s and "b"s must be equal. Did you get it computer?
In the popular (and essential) computer science book, An Introduction to Formal Languages and Automata by Peter Linz, the following formal language is frequently stated:
$$\large{L=\{a^n b^n:n\in\mathbb{Z}^+\}}$$
mainly because this language can not be processed with finite-state automata.
This expression mean "Language L consists all strings of 'a's followed by 'b's, in which the number of 'a's and 'b's are equal and non-zero".
Challenge
Write a working program/function which gets a string, containing "a"s and "b"s only, as input and returns/outputs a truth value, saying if this string is valid the formal language L.

Your program cannot use any external computation tools, including network, external programs, etc. Shells are an exception to this rule; Bash, e.g., can use command line utilities.

Your program must return/output the result in a "logical" way, for example: returning 10 instead of 0, "beep" sound, outputting to stdout etc. More info here.

Standard code golf rules apply.

This is a code-golf. Shortest code in bytes wins. Good luck!
Truthy test cases
"ab"
"aabb"
"aaabbb"
"aaaabbbb"
"aaaaabbbbb"
"aaaaaabbbbbb"

Falsy test cases
""
"a"
"b"
"aa"
"ba"
"bb"
"aaa"
"aab"
"aba"
"abb"
"baa"
"bab"
"bba"
"bbb"
"aaaa"
"aaab"
"aaba"
"abaa"
"abab"
"abba"
"abbb"
"baaa"
"baab"
"baba"
"babb"
"bbaa"
"bbab"
"bbba"
"bbbb"

Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 85994; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

"Your program cannot use any external computation tools , including network , external programs etc" is already in our standard loopholes.

Can the input be empty? (You're saying it's not part of the language, but not whether it's an input we need to consider.)

What if our language doesn't have truthy or falsy? Would empty string == truthy and non-empty string == falsy be acceptable?

@LeakyNun it never hurts to specify it explicitly anyways

I recommend a falsey test case like "aababb". Also please clarify, are concatenations of valid strings valid?

@LLIAMnYP No , they aren't . Only strings in format of ab where a is before b and their counts are equal and non-zero , as explained in main post .

Oh, I see now, I've overlooked an appropriate falsey test case.

Nice challenge, but I think the title could be a little less ambiguous (i.e. a mention of a^n b^n or similar, rather than just the number of as equalling the number of bs)

@Sp3000 I choosed this title because it looked fun . I may change it later to sth else ...

When you say "can not be processed with finite-state automata", you're not talking about finite state automata with loops, right? If you are, how do you explain that I did it in sed?

I'm a little surprised that in 50+ answers I'm the only one to use a paser generator. To be sure it's not strictly competitive on length, but the problem posed is one of parsing a simple but non-trivial language. I'd very much like to see answers in other compiler-compiler syntaxes because I am not widely familiar with the choices.

@someonewithpc this is what I found in Peter Linz's book . I also believe that it's not possible , because the automata must store n in some way . the main problem is that , the count of as and bs must be equal , otherwise it was possible . (note that for a finite possibilities of n it's possible to make a machine with many states that accepts this language, (like a^2k b^2k) but I haven't specified any limit for n . ) also I think your sed answer is actually a Turing machine , but I'm not sure about that.

Is it a given that the string will contain as and bs only? Or do we have to make sure we're not allowing cs and ds?

@SQB I'm not sure that I understood what you meant but input contains nothing other than as and bs .

@GLASSIC He wants to know if the parser needs to be prepared to reject an input like aaabbc (which I have assumed it must), or if it can assume that no c will appear in the input.

@dmckee indeed. One approach could be checking if the second half of the word is the first half of the word, +1 on each letter. (I'm entertaining the thought of a brainf*ck entry).

@dmckee The fact that the Python answer using translate is a valid one, indicates that my assumption is correct. Otherwise printab would be incorrectly deemed a correct input.

What about "rrss" or "rrzz"? It depends from the alphabetical letter too?

MATL, 5 4 bytes
tSP-

Prints a non-empty array of 1s if the string belongs to L, and an empty array or an array with 0s (both falsy) otherwise.
Thanks to @LuisMendo for golfing off 1 byte!
Try it online!
How it works
t      Push a copy of the implicitly read input.
 S     Sort the copy.
  P    Reverse the sorted copy.
   -   Take the difference of the code point of the corresponding characters
       of the sorted string and the original.

My second (working) MATL answer. :)

Strange definition of truthy and falsy:
'aabb' gives -1 -1 1 1 is truthy. 'aaabb' gives -1 -1 0 1 1 and is falsy

@Etoplay A non-empty array with all its values nonzero is truthy. It's the definition used in Matlab and Octave

Python 3, 32 bytes
eval(input().translate(")("*50))

Try it online!
Outputs via exit code: Error for false, no error for True.
The string is evaluated as Python code, replacing parens ( for a and ) for b. Only expressions of the form a^n b^n become well-formed expressions of parentheses like ((())), evaluating to the tuple ().
Any mismatched parens give an error, as will multiple groups like (()()), since there's no separator. The empty string also fails (it would succeed on exec).
The conversion ( -> a, ) -> b is done using str.translate, which replaces characters as indicated by a string that serves as a conversion table. Given  the 100-length string ")("*50, the tables maps the first 100 ASCII values as
... Z[\]^_`abc
... )()()()()(

which takes ( -> a, ) -> b.
In Python 2, conversions for all 256 ASCII values must be provided, requiring "ab"*128, one byte longer; thanks to isaacg for pointing this out.
Try it online! (Python 2, 33 bytes)

Ok, that's clever.

What does the *128 do?

128 can be replaced by 50 (or 99 for that matter) to save a byte.

@Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ: I think it´s a quantifier. But I don´t really know Python and have not found any documentation on that yet.

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ https://docs.python.org/3/library/stdtypes.html#str.translate Basically, the string inside translate gets indexed with the code point of each character of the string to find the translate string. So the string )()()()()()()()... gets created, then indexed at 97 for a and 98 for b.

@isaacg Thanks, I wasn't aware that changed for Python 3.

@Titus strings (https://docs.python.org/3/library/stdtypes.html#textseq) are one sequence type, so you can do all kinds of sequence operations with them (see https://docs.python.org/3/library/stdtypes.html#common-sequence-operations for details). And that is what is happening here: sequence repetition, as explained by the conversion at the end of the answer. (Other examples are "contains" checks: if "lo" in "Hello World": or iteration: for character in "my iterated string":).

Retina, 12 bytes
Credits to FryAmTheEggman who found this solution independently.
+`a;?b
;
^;$

Prints 1 for valid input and 0 otherwise.
Try it online! (The first line enables a linefeed-separated test suite.)
Explanation
Balancing groups require expensive syntax, so instead I'm trying to reduce a valid input to a simple form.
Stage 1
+`a;?b
;

The + tells Retina to repeat this stage in a loop until the output stops changing. It matches either ab or a;b and replaces it with ;. Let's consider a few cases:

If the as and the bs in the string aren't balanced in the same way that ( and ) normally need to be, some a or b will remain in the string, since ba, or b;a can't be resolved and a single a or b on its own can't either. To get rid of all the as and the bs there has to be one corresponding b to the right of each a.
If the a and the b aren't all nested (e.g. if we have something like abab or aabaabbb) then we'll end up with multiple ; (and potentially some as and bs) because the first iteration will find multiple abs to insert them and further iterations will preserve the number of ; in the string.

Hence, if and only if the input is of the form anbn, we'll end up with a single ; in the string.
Stage 2:
^;$

Check whether the resulting string contains nothing but a single semicolon. (When I say "check" I actually mean, "count the number of matches of the given regex, but since that regex can match at most once due to the anchors, this gives either 0 or 1.)

Haskell, 31 bytes
f s=s==[c|c<-"ab",'a'<-s]&&s>""

The list comprehension [c|c<-"ab",'a'<-s] makes a string of one 'a' for each 'a' in s, followed by one 'b' for each 'a' in s. It avoids counting by matching on a constant and producing an output for each match.
This string is checked to be equal to the original string, and the original string is checked to be non-empty.

This is lovely. I often forget how useful it is that Haskell orders the elements of a list comprehension in a consistent and very specific way.

Much nicer than my best attempt (f=g.span id.map(=='a');g(a,b)=or a&&b==(not<$>a)) .  Well done.

Wow, I didn't know one could match on a constant in a list comprehension!

Grime, 12 bytes
A=\aA?\b
e`A

Try it online!
Explanation
The first line defines a nonterminal A, which matches one letter a, possibly the nonterminal A, and then one letter b. The second line matches the entire input (e) against the nonterminal A.
8-byte noncompeting version
e`\a_?\b

After writing the first version of this answer, I updated Grime to consider _ as the name of the top-level expression. This solution is equivalent to the above, but avoids repeating the label A.

Why didn't you do it in J?

@LeakyNun I just wanted to show off Grime. :P

You built this language?

@LeakyNun Yes. Development is slow, but ongoing.

Brachylog, 23 19 bytes
@2L,?lye:"ab"rz:jaL

Try it online!
Explanation
@2L,                  Split the input in two, the list containing the two halves is L
    ?lye              Take a number I between 0 and the length of the input
        :"ab"rz       Zip the string "ab" with that number, resulting in [["a":I]:["b":I]]
               :jaL   Apply juxtapose with that zip as input and L as output
                        i.e. "a" concatenated I times to itself makes the first string of L
                        and "b" concatenated I times to itself makes the second string of L

Congratulations on getting on tryitonline.net!

Bison/YACC 60 (or 29) bytes
(Well, the compilation for a YACC program is a couple of steps so might want to include some for that. See below for details.)
%%
l:c'\n';
c:'a''b'|'a'c'b';
%%
yylex(){return getchar();}

The function should be fairly obvious if you know to interpret it in terms of a formal grammar. The parser accepts either ab or an a followed by any acceptable sequence followed by a b.
This implementation relies on a compiler that accepts K&R semantics to lose a few characters.
It's wordier than I would like with the need to define yylex and to call getchar.
Compile with
$ yacc equal.yacc
$ gcc -m64 --std=c89 y.tab.c -o equal -L/usr/local/opt/bison/lib/ -ly

(most of the options to gcc are specific to my system and shouldn't count against the byte count; you might want to count -std=c89 which adds 8 to the value listed).
Run with
$ echo "aabb" | ./equal

or equivalent.
The truth value is returned to the the OS and errors also report syntax error to the command line. If I can count only the part of the code that defines the parsing function (that is neglect the second %% and all that follows) I get a count of 29 bytes.

J, 17 15 bytes
-2 bytes thanks to Jonah!
#<.2&#-:'ab'#~#

This works correctly for giving falsey for the empty string. Error is falsey.
Other versions:
<e.'ab'<@#"{~#\       NB. alternate 15 bytes, thanks to Jonah
#<.(-:'ab'#~-:@#)

NB. the following do not handle the empty string correctly
-:'ab'#~-:@#
2&#-:'ab'#~#          NB. thanks to miles

Proof and explanation
Outdated, but applicable to the old 17 byte version.
The main verb is a fork consisting of these three verbs:
# <. (-:'ab'#~-:@#)

This means, "The lesser of (<.) the length (#) and the result of the right tine ((-:'ab'#~-:@#))".
The right tine is a 4-train, consisting of:
(-:) ('ab') (#~) (-:@#)

Let k represent our input. Then, this is equivalent to:
k -: ('ab' #~ -:@#) k

-: is the match operator, so the leading -: tests for invariance under the monadic fork 'ab' #~ -:@#.
Since the left tine of the fork is a verb, it becomes a constant function. So, the fork is equivalent to:
'ab' #~ (-:@# k)

The right tine of the fork halves (-:) the length (#) of k. Observe #:
   1 # 'ab'
'ab'
   2 # 'ab'
'aabb'
   3 # 'ab'
'aaabbb'
   'ab' #~ 3
'aaabbb'

Now, this is k only on valid inputs, so we are done here. # errors for odd-length strings, which never satisfies the language, so there we are also done.
Combined with the lesser of the length and this, the empty string, which is not a part of our language, yields its length, 0, and we are done with it all.

I modified it into 2&#-:'ab'#~# which should let you avoid the error and just output 0 instead while still using 12 bytes.

@miles Fascinating! I never thought about it like that.

Does this handle the empty string?

@Zgarb fixed it!

-2 bytes: <e.'ab'<@#"{~#\ -- Try it online!

Another 15 using miles version + your empty string special case: #<.2&#-:'ab'#~#

@Jonah Nice approaches!

05AB1E, 9 bytes
Code:
.M{J¹ÔQ0r

Explanation:
.M         # Get the most frequent element from the input. If the count is equal, this
           results into ['a', 'b'] or ['b', 'a'].
  {        # Sort this list, which should result into ['a', 'b'].
   J       # Join this list.
    Ô      # Connected uniquified. E.g. "aaabbb" -> "ab" and "aabbaa" -> "aba".
     Q     # Check if both strings are equal.
      0r   # (Print 0 if the input is empty).

The last two bytes can be discarded if the input is guaranteed to be non-empty.
Uses the CP-1252 encoding. Try it online!.

What happens with empty input?

Look for non-zero in the post; it’s in there :)

@Lynn Doesn't the spec only say no-zero for a valid language though? Not about input.

True. Thought wrong there. But you can still do .M{J¹ÔQ0r for yours.

@Emigna Thanks, I have edited the post.

This returns truthy for both b and a.

Jelly, 6 bytes
Ṣ=Ṛ¬Pȧ

Prints the string itself if it belongs to L or is empty, and 0 otherwise.
Try it online! or verify all test cases.
How it works
Ṣ=Ṛ¬Pȧ  Main link. Argument: s (string)

Ṣ       Yield s, sorted.
  Ṛ     Yield s, reversed.
 =      Compare each character of sorted s with each character of reversed s.
   ¬    Take the logical NOT of each resulting Boolean.
    P   Take the product of the resulting Booleans.
        This will yield 1 if s ∊ L or s == "", and 0 otherwise.
     ȧ  Take the logical AND with s.
       This will replace 1 with s. Since an empty string is falsy in Jelly,
       the result is still correct if s == "".

Alternate version, 4 bytes (non-competing)
ṢnṚȦ

Prints 1 or 0. Try it online! or verify all test cases.
How it works
ṢnṚȦ  Main link. Argument: s (string)

Ṣ     Yield s, sorted.
  Ṛ   Yield s, reversed.
 n    Compare each character of the results, returning 1 iff they're not equal.
   Ȧ  All (Octave-style truthy); return 1 if the list is non-empty and all numbers
      are non-zero, 0 in all other cases.

JavaScript, 54 55 44
s=>s&&s.match(`^a{${l=s.length/2}}b{${l}}$`)

Builds a simple regex based on the length of the string and tests it. For a length 4 string (aabb) the regex looks like: ^a{2}b{2}$
Returns a truthy or falsey value.
11 bytes saved thanks to Neil.

f=s=>s&&s.match(`^a{${l=s.length/2}}b{${l}}$`)
// true
console.log(f('ab'), !!f('ab'))
console.log(f('aabb'), !!f('aabb'))
console.log(f('aaaaabbbbb'), !!f('aaaaabbbbb'))
// false
console.log(f('a'), !!f('a'))
console.log(f('b'), !!f('b'))
console.log(f('ba'), !!f('ba'))
console.log(f('aaab'), !!f('aaab'))
console.log(f('ababab'), !!f('ababab'))
console.log(f('c'), !!f('c'))
console.log(f('abc'), !!f('abc'))
console.log(f(''), !!f(''))

The f= can be omitted.

Is a function expression a valid submission, or must it actually be, ahem, functional?

A function is a valid submission.

@TimmyD It used to return true, but now it returns false.

s.match will turn your string into a regexp for you. Also, I think using a template string might save you a couple of bytes.

@Neil Thanks! Didn't realize that about s.match.

Using RegExp to match for an irregular language :>) so evil

s=>s.match(`^a{${s.length/2}}b+$`)?

Perl 5.10, 35 17 bytes (with -n flag)
say/^(a(?1)?b)$/

Ensures that the string starts with as and then recurses on bs. It matches only if both lengths are equal.
Thanks to Martin Ender for halving the byte count and teaching me a little about recursion in regexes :D
It returns the whole string if it matches, and nothing if not.
Try it here!

Closest I can manage including the non-empty test case is 18 bytes: $_&&=y/a//==y/b// (requires -p), without the empty you could drop the && for 16! So close...

So I can do another 17 bytes: echo -n 'aaabbb'|perl -pe '$_+=y/a//==y/b//' but I can't shift another byte... Might have to give up on this!

Just realised that this could be done in 7 bytes using that regex as -F/^(a(?1)?b)$/: https://tio.run/##LYw9CoVADIT7nMNCCxGLV/pTeQwlAQtBdFHPb9yZPFgyk518k9Zr/7kXSzdOfeuuJqqGkScFGobub8ObiAp@xPJjBFw0r2gxJlkZB8pqXOFEOQAEQQQMIJwYa9gTRdFk8p7p2c7j9jrtUzOXWg5tNVhVNB8

C, 57 53 Bytes
t;x(char*s){t+=*s%2*2;return--t?*s&&x(s+1):*s*!1[s];}

Old 57 bytes long solution:
t;x(char*s){*s&1&&(t+=2);return--t?*s&&x(s+1):*s&&!1[s];}

Compiled with gcc v. 4.8.2 @Ubuntu
Thanks ugoren for tips!
Try it on Ideone!

Since I'm new here and can't comment on other answers yet, I just want to point out that 62b solution from @Josh gives false positive on strings like "aaabab".

Change (t+=2) to t++++ for -1 byte.

@owacoder t++++ is not a valid C code.

Save some with t+=*s%2*2 and :*s*!1[s]

Very clever answer!  It does unfortunately fail on input "ba" : http://ideone.com/yxixG2

The purpose of this post is to demonstrate and explain the full list of golfed pure regexes that solve this challenge, and the range of compatibility of each among seven different regex engines, and rank them by length, all together in one post. Others' answers used the best regexes before this post; they are listed below. I ported the Java one to three other sets of regex engines, including Python 3's regex library.
Regex (Perl / PCRE / Boost / Pythonregex), 11 bytes
^(a(?1)?b)$

Try it online! - Perl
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Boost
Try it online! - Python import regex
Included for completeness. Already used in:

Martin Ender's Mathematica answer
Titus's PHP answer
Paul Picard's Perl answer

^          # Assert we're at the beginning of the string.
(          # Define subroutine (?1):
    a      # Match one 'a'.
    (?1)?  # Optionally do a recursive subroutine call to (?1).
    b      # Match one 'b'.
)
$          # Assert we're at the end of the string.

When the regex engine hits the (?1)?, it has the choice of whether to do the call or not. Due to ? being greedy by default, it first tries doing the call; if it then hits a b character instead of an a, it will backtrack, avoid doing the subroutine call, and then reach the part of the regex that matches a b character.
From that point forward, it will keep popping out of the recursive call stack, matching another b each time. This way, the number of times that it attempts to match b equals the number of a it matched at the beginning.
If it finds an a when attempting to match b, this will trigger a non-match. If it finishes popping and still finds more b characters, this will trigger a non-match at the $ part of the regex. If it reaches the end of the string prematurely during this stage, it will pop out from that call and attempt to match another b, thus triggering a non-match.
The only backtracking left to be tried at the popping-out stage, in the case of any of those non-matches, is to stop calling (?1) at an earlier point, but this will also fail to match, as it will then be trying to match a where the string has a b; this will result in a top-level non-match.
Regex (PCRE / Ruby), 12 bytes
^(a\g<1>?b)$

Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Ruby
Included for completeness. Already used in G B's Ruby answer.
This is the same as the 11 byte version, but using Ruby's subroutine call syntax.
Regex (Perl / PCRE / Java), 21 bytes
^(a(?=a*(\2?+b)))+\2$

Try it online! - Perl
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Java
Turned out to be used in Kevin Cruijssen's Java answer, but gave it a -6 byte golf.
This regex is the next-best thing to recursion, in engines that lack it. It works using group-building:
^           # Assert we're at the beginning of the string.
(
    a       # Match one more 'a' per each iteration of this loop.
    # Lookahead assertion - when this finishes, the regex engine's "cursor"
    # will jump back to the same position as it was in when it entered the
    # lookahead here. It's atomic, so the regex engine can't backtrack into
    # the lookahead once it has completed its match or non-match. This means
    # the main loop will exit immediately if this lookahead fails to match
    # (due to running out of 'b' characters to match), or if the 'a' above
    # fails to match.
    (?=
        a*      # Skip over as many 'a' as necessary to get to the first 'b'.
        # Capture \2, embedding within it the previous contents of itself.
        # If this is the first iteration, \2 will be unset, so capture a
        # single 'b' in \2. Otherwise, append one more 'b' to the previous
        # contents of \2.
        (
            \2?+    # Optionally match \2, but if it does match, lock that
                    # match in (don't backtrack to here and try not making the
                    # match, in the case that a non-match occurs after this
                    # point). This is guaranteed to fail to match if and only if
                    # we're on the first iteration, due to \2 being unset. On
                    # subsequent iterations, since \2 will have been captured
                    # starting at the first non-'a' character, and always starts
                    # its attempted match there, it will be guaranteed to match.
            b       # Match one 'b'.
        )
    )
)+
\2          # Match however many 'b' we captured in \2.
$           # Assert we're at the end of the string.

Regex (.NET), 22 bytes
^(a)+(?<-1>b)+$(?(1)^)

Try it online!
Included for completeness. Already used in:

Leaky Nun's Retina answer
AdmBorkBork's PowerShell answer
Dion Williams's C# answer (with regex 7 bytes longer than it needs to be)

This regex uses the Balancing Groups feature of the .NET regex engine:
^           # Assert we're at the beginning of the string.

(a)+        # Match as many 'a' characters as we can, minimum of one, pushing
            # each single-character capture onto the Group 1 capture stack.

(?<-1>b)+   # Pop the Group 1 capture stack as many times as we can, matching
            # a single 'b' each time. This will stop looping when it hits a
            # character other than 'b', or empties the Group 1 capture stack.

$           # Assert we're at the end of the string. If this fails to match
            # (meaning there are more 'b' characters than 'a' characters), the
            # regex engine will backtrack, but none of the choices it has will
            # be able lead to a match, so there will be a top-level non-match.

(?(1)^)     # If there are any remaining captures on the Group 1 stack (which
            # means there were fewer 'b' characters than 'a' chracters), assert
            # something which can never be true - that we're at the beginning
            # of the string. Since the first thing the regex did was capture at
            # least one 'a', the fact that we've reached this point means that
            # was already done, so it's impossible for us to be at the beginning
            # of the string. Thus this causes a non-match in the case that there
            # are fewer 'b' than 'a'.

Some people use this regex in the form of ^(a)+(?<-1>b)+(?(1)^)$, i.e. with the $ at the end rather than the beginning, but I prefer ^(a)+(?<-1>b)+$(?(1)^), since it tries the slightly-less-complicated operation of $ first, so in the case of a non-match, it will be ever so slightly more efficient. In theory.
The ^ in the (?(1)^) can be replaced with various other things that can't match, such as (?(1).) or (?(1)c).
Regex (Perl / PCRE / Java / .NET), 24 bytes
^(a(?=a*((?>\2?)b)))+\2$

Try it online! - Perl
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Java
Try it online! - .NET
This is a port of the 21 byte Perl/PCRE/Java regex, with \3?+ changed to (?>\3?) to allow the regex to also work on .NET (which lacks possessive quantifiers).
Regex (Perl / PCRE / Java / Ruby / Pythonregex), 29 bytes
^(a(?=a*(?=(\3?+b))(\2)))+\2$

Try it online! - Perl
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Java
Try it online! - Ruby
Try it online! - Python import regex
This is a port of the 21 byte Perl/PCRE/Java regex (see below) adding compatibility with engines that lack nested backreferences, but still have forward-declared backreferences and possessive quantifiers. This allows it to work in Python when using the regex library instead of re.
^           # Assert we're at the beginning of the string.
(
    a       # Match one 'a' per iteration of this loop.
    (?=
        a*  # Skip over as many 'a' as necessary to get to the first 'b'.
        (?=
            # Capture \2. If this is the first iteration, \3 will be unset, so
            # capture a single 'b' in \2. Otherwise, \2 = \3 concatenated with
            # one more 'b'.
            (
                \3?+
                b
            )
        )
        # \3 = make a copy of \2, which was captured above
        (
            \2
        )
    )
)+
\2          # Match however many 'b' we captured in \2.
$           # Assert we're at the end of the string.

Regex (Perl / PCRE / Java / Ruby / Pythonregex / .NET), 32 bytes
^(a(?=a*(?=((?>\3?)b))(\2)))+\2$

Try it online! - Perl
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Java
Try it online! - Ruby
Try it online! - Python import regex
Try it online! - .NET
This is a port of the above, with \3?+ changed to (?>\3?) to allow the regex to work on .NET (which lacks possessive quantifiers), so it can support 6 different regex engines at once.
It is not supported by Boost, which lacks both forward-declared and nested backreferences. It might not be possible for a single regex to work on all 7 engines.

Vyxal, 7 6 5 4 bytes
I÷<g

Try it Online!
Try it Online! - without the f header
Takes a list of characters as input. Outputs 1 for true for inputs in \$\{a^n b^n:n∈\mathbb{Z}^+\}\$, and empty string or 0 for false otherwise. This matches Vyxal's truthy/falsey semantics, which can be confirmed by putting ḃ (Boolify) in the Footer.
I   # Into Two Pieces - Splits a list into two halves and wraps them in a list.
    # If the input is odd in length, the left side gets 1 more character.
÷   # Item Split - Unwraps the list created above. Required so that the next
    # operation can compare the two halves.
<   # Less Than (vectorized) - Are items in the left half list less than the
    # corresponding items in the right half list? Puts 1 where yes, 0 where no.
    # The resulting list takes the size of whichever list was longer. For items
    # at the end of that list with no corresponding item in the other list, it
    # puts 0 if that position is empty in the right list, and 1 if it's empty in
    # the left list (which can never happen in this program).
g   # Minimum

Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in 4 bytes:
I÷<A

Try it Online!
Try it Online! - without the f header
Takes a list of characters as input. Outputs 1 for true and 0 for false. Only the last element of the program is different:
A   # Check if all items in a list are truthy (returns truthy for an empty list)

Vyxal, 6 5 4 bytes
sṘ꘍g

Try it Online!
Try it Online! - without the f: header
Takes a list of characters as input. Outputs 1 for true for inputs in \$\{a^n b^n:n∈\mathbb{Z}^+\}\$, and empty string or 0 for false otherwise.
This is a port of Dennis's MATL answer, with an algorithm also used by many subsequent answers.
s   # Pushes a copy of the input, sorted.
Ṙ   # Reverses the sorted copy.
꘍   # Levenshtein distance (vectorized) - Used here to compare corresponding
    # single-character strings between two lists, so it's effectively a vectorized
    # Not Equals, giving 1 for unequal and 0 for equal. This works around the fact
    # that Vyxal has no vectorizing Not Equals operator (even though it does have
    # vectorizing versions of all the other basic comparison operators). For input
    # in L, this will yield a non-empty list of all 1s. For an empty input it will
    # yield an empty list. For all other inputs it yields a list of both 1s and 0s.
g   # Minimum

To take a string as input, this becomes f:sṘ꘍g or alternatively fṘḂs꘍g (6 bytes). It is, however, possible to do this with the sort-and-reverse algorithm in 5 bytes (see AḂs꘍↓ below).

Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in 4 bytes using this algorithm:
sṘ꘍A

Try it Online!
Try it Online! - without the f: header
Takes a list of characters as input. Outputs 1 for true and 0 for false.
To take a string as input, this becomes f:sṘ꘍A or alternatively fṘḂs꘍A (6 bytes). It is, however, possible to do this with the sort-and-reverse algorithm in 5 bytes (see AḂs꘍A below).
Vyxal, 5 bytes
fI÷<g

Try it Online!
Takes a string as input. Outputs 1 for true for inputs in \$\{a^n b^n:n∈\mathbb{Z}^+\}\$, and empty string or 0 for false otherwise. This is just one of the above 4 byte programs with f inserted at the beginning.

Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in this way:
fI÷<A

Try it Online!
Takes a string as input. Outputs 1 for true and 0 for false.
This too is just one of the above 4 byte programs with f inserted at the beginning – but it can also be done without f, using a conceptually similar algorithm:
½C÷‹⁼

Try it Online!
Takes a string as input. Outputs 1 for true and 0 for false.
½   # Split in half. If odd in length, the left side gets 1 more character. This
    # creates a list containing two strings.
C   # Convert characters to their ASCII values. This results in a list containing
    # two lists of ASCII values.
÷   # Item Split - split the list into its elements on stack; in this case, these
    # are the left and right halves, each of which is a list of ASCII values.
‹   # Decrement - iff the right half is all 'b' (ASCII 98), this will change it to
    # all 'a' (ASCII 97)
⁼   # Are the two top items on the stack exactly equal? This gives a boolean value
    # that's 1 for true (equal counts of 'a' and 'b') and 0 for false.

Vyxal, 5 bytes
AḂs꘍↓

Try it Online!
Takes a string as input. Outputs 1 for true, and empty string or 0 for false.
This is an adaptation of the algorithm used in Dennis's Jelly answer and MATL answer (and many subsequent answers):
A   # Check if character is a vowel (vectorized)
    # Converts each 'a' to 1, and each 'b' to 0. Pushes the result as a list if
    # the input was a string of 2 characters or longer, but only pushes a single
    # integer if it was a single-character string. This limits what useful
    # operations can subsequently be done (for example, it can't be reliably
    # split into two halves).
Ḃ   # Bifurcate - Pushes the top of the stack then its reverse.
s   # Sort - Operates on the non-reversed copy.
꘍   # Bitwise Xor (vectorized)
↓   # Minimum by tail. On a list of numbers, it picks the item with the minimum
    # last digit. On a single number, it picks the minimum digit. Since the only
    # numbers given to it here will be 0 and 1, that's the same as the standard
    # minimum, except that it avoids the crash that happens with "g" (Minimum)
    # when its argument is not a list.

It appears to be impossible to solve this challenge in Vyxal in less than 5 bytes taking a string as input.

Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in this way:
AḂs꘍A

Try it Online!
Takes a string as input. Outputs 1 for true and 0 for false. Only the last element of the program is different:
A   # Check if all items in a list are truthy (returns truthy for an empty list)

Mathematica, 45 bytes
#~StringMatchQ~RegularExpression@"(a(?1)?b)"&

Another recursive regex solution. This doesn't need anchors because StringMatchQ achors it implicitly, but unfortunately it just seems to do wrap the regex in ^(?:...)$ which means we can't use (?R) for the recursion, as that gets the anchors as well. Hence the seemingly useless group around the entire regex, so we can access only that part for the recursion.

Retina, 22 bytes
Another shorter answer in the same language just came...
^(a)+(?<-1>b)+(?(1)c)$

Try it online!
This is a showcase of the balancing groups in regex, which is explained fully by Martin Ender.
As my explanation would not come close to half of it, I'll just link to it and not attempt to explain, as that would be detrimental to the glory of his explanation.

C, 69 bytes
69 bytes:
#define f(s)strlen(s)==2*strcspn(s,"b")&strrchr(s,97)+1==strchr(s,98)
For those unfamiliar:

strlen determines the length of the string
strcspn returns the first index in string where the other string is found
strchr returns a pointer to the first occurrence of a character
strrchr returns a pointer to the last occurrence of a character

A big thanks to Titus!

save one byte with >97 instead of ==98

61 bytes solution gives false positive on strings like "aaabab". See http://ideone.com/nmT8rm

Ah you are correct Jasmes, thanks.  I will have to rethink this a little.

Reverting back to the 69 byte solution, not sure if I can get any shorter using this approach.

Befunge-93, 67 bytes
0v@.<  0<@.!-$<  >0\v
+>~:0`!#^_:"a" -#^_$ 1
~+1_^#!-"b" _ ^#`0: <

Try it here! Might explain how it works later. Might also try to golf it just a tad bit more, just for kicks.

Nekomata + -e, 3 bytes
N;<

Attempt This Online!
N;<
N       Check nonempty
 ;      Split the list into two parts
  <     Check elementwise less than; fails if their lengths are different

MATL, 9 bytes
vHI$e!d1=

Try it online!
The output array is truthy if it is non-empty and all its entries are nonzero. Otherwise it's falsy. Here are some examples.
v     % concatenate the stack. Since it's empty, pushes the empty array, []
H     % push 2
I$    % specify three inputs for next function
e     % reshape(input, [], 2): this takes the input implicitly and reshapes it in 2
      % columns in column major order. If the input has odd length a zero is padded at
      % the end. For input 'aaabbb' this gives the 2D char array ['ab;'ab';'ab']
!     % transpose. This gives ['aaa;'bbb']
d     % difference along each column
1=    % test if all elements are 1. If so, that means the first tow contains 'a' and
      % the second 'b'. Implicitly display

That's some convenient definition of truthy. (I knew about the non-zero requirement, but not about the non-empty one.)

Java 8, 69 37 bytes
 s->s.matches("(a(?=a*(\\2?+b)))+\\2")

Regex shamelessly 'borrowed' from here.
-6 bytes thanks to @Deadcode, plus a bit more by converting Java 7 to 8
Try it online.
Explanation:
s->                   // Method with String parameters and boolean return-type
  s.matches("...")    //  Check if the String matches the regex explained below

Regex explanation:
^                   $ # (implicit by String#matches: match entire String)
                 +    # Repeat one or more times:
 (              )     #  Capture group 1, which does:
  a                   #   Match an 'a'
   (?=         )      #    With a positive look-ahead to:
      a*              #     0 or more 'a's
        (     )       #     Followed by, in capture group 2:
         \2           #      The value of capture group 2,
           ?+         #      zero or one times, giving prio to one, without backtracking
             b        #      Following by a 'b'
                  \2  # Followed by the value of capture group 2 (the 'b's)

-6 bytes. The eXtended flag isn't needed, as there's no whitespace in the regex.

And of course, 37 bytes in Java 8.

Why does the static  get to be excluded from the Java 7 version's byte length? It doesn't work without it, at least in the code snippet you provided.

@Deadcode Thanks for the -6. :) As for the question in your final comment: the static is just there for convenient. If you replace all c(...) calls to new Main().c(...) calls it works without the static: try it online.

Before you ask about the downvote, it was a misclick that I didn't notice until it showed up as a rep change...

@UnrelatedString I've made a minor edit in case you want to change your downvote to an upvote.

JavaScript, 44 42
Crossed out 44 is still regular 44 ;(
f=s=>(z=s.match`^a(.+)b$`)?f(z[1]):s=="ab"

Works by recursively stripping off the outer a and b and recursively using the inner value selected but .+. When there's no match on ^a.+b$ left, then the final result is whether the remaining string is the exact value ab.
Test cases:
console.log(["ab","aabb","aaabbb","aaaabbbb","aaaaabbbbb","aaaaaabbbbbb"].every(f) == true)
console.log(["","a","b","aa","ba","bb","aaa","aab","aba","abb","baa","bab","bba","bbb","aaaa","aaab","aaba","abaa","abab","abba","abbb","baaa","baab","baba","babb","bbaa","bbab","bbba","bbbb"].some(f) == false)

x86 machine code, 29 27 bytes
Hexdump:
33 c0 40 41 80 79 ff 61 74 f8 48 41 80 79 fe 62
74 f8 0a 41 fe f7 d8 1b c0 40 c3

Assembly code:
    xor eax, eax;
loop1:
    inc eax;
    inc ecx;
    cmp byte ptr [ecx-1], 'a';
    je loop1;

loop2:
    dec eax;
    inc ecx;
    cmp byte ptr [ecx-2], 'b';
    je loop2;

    or al, [ecx-2];
    neg eax;
    sbb eax, eax;
    inc eax;
done:
    ret;

Iterates over the a bytes in the beginning, then over the following 'b' bytes. The first loop increases a counter, and the second loop decreases it. Afterwards, does a bitwise OR between the following conditions:

If the counter is not 0 at the end, the string doesn't match
If the byte that follows the sequence of bs is not 0, the string also doesn't match

Then, it has to "invert" the truth value in eax - set it to 0 if it was not 0, and vice versa. It turns out that the shortest code to do that is the following 5-byte code, which I stole from the output of my C++ compiler for result = (result == 0):
    neg eax;      // negate eax; set C flag to 1 if it was nonzero
    sbb eax, eax; // subtract eax and the C flag from eax
    inc eax;      // increase eax

I think you can improve your negation.  Try: neg eax to set the carry flag as before, cmc to invert the carry flag and salc to set AL to FFh or 0 depending on whether the carry flag is set or not.  Saves 2 bytes, although does end up with an 8-bit result rather than 32-bit.

The same thing using string ops, with ESI pointing to the input string, and returning the result in AL (uses SETcc, requires 386+): xor eax,eax | xor ecx,ecx | l1: inc ecx | lodsb | cmp al, 'a' | jz l1 | dec esi | l2: lodsb | cmp al,'b' | loopz l2 | or eax,ecx | setz al | ret

@ninjalj You should post that in an answer - it's sufficiently different from mine, and I suspect is significantly shorter!

Ruby, 24 bytes
eval(gets.tr'ab','[]')*1

(This is just xnor's brilliant idea in Ruby form. My other answer is a solution I actually came up with myself.)
The program takes the input, transforms a and b to [ and ] respectively, and evaluates it.
Valid input will form a nested array, and nothing happens. An unbalanced expression will make the program crash. In Ruby empty input is evaluated as nil, which will crash because nil has not defined a * method.

R, 64 61 55 bytes, 73 67 bytes (robust) or 46 bytes (if empty strings are allowed)

Again, xnor's answer reworked. If it is implied by the rules that the input will consist of a string of as and bs, it should work: returns NULL if the expression is valid, throws and error or nothing otherwise.
if((y<-scan(,''))>'')eval(parse(t=chartr('ab','{}',y)))

If the input is not robust and may contain some garbage, e.g. aa3bb, then the following version should be considered (must return TRUE for true test cases, not NULL):
if(length(y<-scan(,'')))is.null(eval(parse(t=chartr("ab","{}",y))))

Finally, if empty strings are allowed, we can ignore the condition for non-empty input:
eval(parse(text=chartr("ab","{}",scan(,''))))

Again, NULL if success, anything else otherwise.

I don´t know R, what´s your result for empty input? (should be falsy)

Is there really no shorter way to test for empty input?

Version 1: just nothing (correct input returns only NULL), version 2: just nothing (correct input returns only TRUE), version 3 (assuming empty strings are OK, as state): NULL. R is a statistical object-oriented language that typecasts everything just OK, without any warning.

This (answer 1) can be further improved to 55 bytes: if((y<-scan(,''))>'')eval(parse(t=chartr('ab','{}',y)))

Sed, 38 + 2 = 40 bytes
s/.*/c&d/;:x;s/ca(.*)bd/c\1d/;tx;/cd/p

A non empty string output is truthy
Finite state automata can not do this, you say? What about finite state automata with loops. :P
Run with r and n flags.
Explanation
s/.*/c&d/        #Wrap the input in 'c' and 'd' (used as markers)
:x               #Define a label named 'x'
s/ca(.*)bd/c\1d/ #Deletes 'a's preceded by 'c's and equivalently for 'b's and 'd's. This shifts the markers to the center
tx               #If the previous substitution was made, jump to label x
/cd/p            #If the markers are next to one another, print the string

Nice approach. Thanks for the breakdown.

ANTLR, 31 bytes
grammar A;r:'ab'|'a'r'b'|r'\n';

Uses the same concept as @dmckee's YACC answer, just slightly more golfed.
To test, follow the steps in ANTLR's Getting Started tutorial. Then, put the above code into a file named A.g4 and run these commands:
$ antlr A.g4
$ javac A*.java

Then test by giving input on STDIN to grun A r like so:
$ echo "aaabbb" | grun A r

If the input is valid, nothing will be output; if it is invalid, grun will give an error (either token recognition error, extraneous input, mismatched input, or no viable alternative).
Example usage:
$ echo "aabb" | grun A r
$ echo "abbb" | grun A r
line 1:2 mismatched input 'b' expecting {<EOF>, '
'}

Clever trick adding the newline as an alternate in a single rule. I think I could save a few that way in yacc, too. The grammer keyword is a stinker for golfing with antlr, though. Kinda like using fortran.

Japt, 11 bytes
©¬n eÈ¦Ug~Y

Try it online!
Gives either true or false, except that "" gives "" which is falsy in JS.
Unpacked & How it works
U&&Uq n eXYZ{X!=Ug~Y

U&&     The input string is not empty, and...
Uq n    Convert to array of chars and sort
eXYZ{   Does every element satisfy...?
X!=       The sorted char does not equal...
Ug~Y      the char at the same position on the original string reversed

Adopted from Dennis' MATL solution.

Prolog (SWI), 34 33 bytes
-[].
-L:-append([97|M],`b`,L),-M.

Try it online!

Brachylog (newer), 11 10 6 bytes
o?ḅĊlᵛ

Try it online!
The predicate succeeds if the input is in L and fails otherwise.
          The input
o         sorted
 ?        is the input,
  ḅ       and the runs in the input
   Ċ      of which there are two
    lᵛ    have the same length.

At this rate you will catch up to my number of Brachylog answers in a few days!

That use of ᵛ is really clever!

@DLosc Thanks! z₂ didn't exist yet ;)

05AB1E, 6 bytes
ÇÂs{αß

Only 1 is truthy in 05AB1E, and it'll output 0 (or "" for the empty string) as falsey.
Try it online or verify all test cases.
Explanation:
Ç       # Convert the (implicit) input-string to a list of integer codepoints
        #  i.e. "aaabbb" → [97,97,97,98,98,98]
        #  i.e. "baba" → [98,97,98,97]
        #  i.e. "aab" → [97,97,98]
        #  i.e. "" → []
 Â      # Bifurcate this list (short for Duplicate & Reverse copy)
        #  STACK: [[97,97,97,98,98,98], [98,98,98,97,97,97]]
        #  STACK: [[98,97,98,97], [97,98,97,98]]
        #  STACK: [[97,97,98], [98,97,97]]
        #  STACK: [[], []]
  s     # Swap to get the duplicated list
        #  STACK: [[98,98,98,97,97,97], [97,97,97,98,98,98]]
        #  STACK: [[97,98,97,98], [98,97,98,97]]
        #  STACK: [[98,97,97], [97,97,98]]
        #  STACK: [[], []]
   {    # Sort it
        #  STACK: [[98,98,98,97,97,97], [97,97,97,98,98,98]]
        #  STACK: [[97,98,97,98], [97,97,98,98]]
        #  STACK: [[98,97,97], [97,97,98]]
        #  STACK: [[], []]
    α   # Take the absolute difference at the same positions
        #  STACK: [[1,1,1,1,1,1]]
        #  STACK: [[0,1,1,0]]
        #  STACK: [[1,0,1]]
        #  STACK: [[], []]
     ß  # And take the minimum, which will be 1 if all were truthy;
        # 0 if any were falsey; or an empty string if the list is empty
        #  STACK: [1]
        #  STACK: [0]
        #  STACK: [0]
        #  STACK: [""]
        # (after which it is output implicitly as result)

C (Ansi), 65 75 Bytes
Golfed:
l(b,i,j,k)char*b;{for(i=j=0;(k=b[i++])>0&k<=b[i];)j+=2*(k>97)-1;return !j;}

Explanation:
Sets a value j and increments j on each b and decrements j on anything else.
Checked if the letter before is less than or equal the next letter so prevent abab from working
Edits
Added checks for abab cases.

Won't this give false positives on strings like ba or abab?

Ahh yes, I misread the post since I could not see the picture since its blocked for me. Fixing it!

Python 2, 43 40 Bytes
lambda s:''<s==len(s)/2*"a"+len(s)/2*"b"

Try it online! - considered the obvious solution thanks to Leaky Nun
other idea, 45 bytes:
lambda s:s and list(s)==sorted(len(s)/2*"ab")

Try it online!
-4 bytes by using len/2 (i get an error when the half comes last)
now gives false for the empty string
-3 bytes thanks to xnor

Yes, lambdas don't have to be named.

lambda s:list(s)==sorted("ab"*len(s)//2) (Python 3)

lambda s:s=="a"*len(s)//2+"b"*len(s)//2 (Python 3)

yeah, I realized that while posting it. lol, the obvious solution is shorter in Python 2:

lambda s:s=="a"*len(s)/2+"b"*len(s)/2 if you accept errors as falsey

lambda s:s==len(s)/2*"a"+len(s)/2*"b" # (Python 2, no errors)

What happens with empty input?

Doesn't this incorrectly give True for the empty string?

it's true, damn have to change that

fix: but there has to be a shorter way: lambda s:s and s==len(s)/2*"a"+len(s)/2*"b"

You can do ''< instead of s and to rule out the empty case.

Batch, 133 bytes
@if ""=="%1" exit/b1        Fail if the input is empty
@set a=%1                   Grab the input into a variable for processing
@set b=%a:ab=%              Remove all `ab` substrings
@if "%a%"=="%b%" exit/b1    Fail if we didn't remove anything
@if not %a%==a%b%b exit/b1  Fail if we removed more than one `ab`
@if ""=="%b%" exit/b0       Success if there's nothing left to check
@%0 %b%                     Rinse and repeat

Returns an ERRORLEVEL of 0 on success, 1 on failure. Batch doesn't like to do substring replacement on empty strings, so we have to check that up front; if an empty parameter was legal, line 6 wouldn't be necessary.

PowerShell v2+, 61 52 bytes
param($n)$x=$n.length/2;$n-and$n-match"^a{$x}b{$x}$"

Takes input $n as a string, creates $x as half the length. Constructions an -and Boolean comparison between $n and a -match regex operator against the regex of an equal number of a's and b's. Outputs Boolean $TRUE or $FALSE. The $n-and is there to account for ""=$FALSE.
Alternate, 35 bytes
$args-match'^(a)+(?<-1>b)+(?(1)c)$'

This uses the regex from Leaky's answer, based on .NET balancing groups, just encapsulated in the PowerShell -match operator. Returns the string for truthy, or empty string for falsey.

In the alternate version you should evaluate -match against $args[0], otherwise -match will work as a filter

@MathiasR.Jessen In production code, yes, but we can golf the [0] here because we're only given one input and we only need one truthy/falsey value as output. Since an empty string is falsey and a non-empty string is truthy, we can filter against the array and either get the input string back or nothing back, which satisfies the challenge requirements.

Pyth - 13 bytes
&zqzS*/lz2"ab

Explained:
  qz          #is input equal to
          "ab #the string "ab"
     *        #multiplied by
      /lz2    #length of input / 2
    S         #and sorted?
&z            #(implicitly) print if the above is true and z is not empty

You can use a string as input and then make it &qS*/lQ2"ab

@LeakyNun thanks for the tip! Can you explain how/why that works? This is my first time ever using Pyth

For example, +4 will expand to +4Q (implicit filling of arguments)

Haskell, 39 bytes
p x=elem x$scanl(\s _->'a':s++"b")"ab"x

Usage example: p "aabb" -> True.
scanl(\s _->'a':s++"b")"ab"x build a list of all ["ab", "aabb", "aaabbb", ...] with a total of (length x) elements. elem checks if x is in this list.

C, 65 bytes
m,t;C(char*c){for(m=1,t=0;*c;)m>0&*c++-97&&(m-=2),t+=m;return!t;}

m---- doesn't compile.

@ugoren what compiler are you using?

gcc on Linux says error: invalid lvalue in decrement. Does any compiler compile this?

Whoopsie, correct, nice catch @ugoren, I must have missed the error among the warnings. Reverted to the 65 byte solution.

Octave, 28 bytes
@(m)diff(+m)>=0&~sum(m-97.5)

This defines an anonymous function. It works also for empty input. Falsy and truthy are as described in my MATL answer.
Try it at ideone.
Explanation
diff(+m)>0 checks if the input string (consisting of 'a' and 'b') is sorted, that is, all characters 'a' come before all 'b'.
The other condition that needs to be checked is whether the numbers of characters 'a' and 'b' are the same. Since their ASCII codes are 97 ansd 98, this is done subtracting 97.5 and chacking if the the sum is zero.
For empty input the result is empty, which is falsy.

Mathematica 83 80 68 54 bytes
#&@@@#<>""=="ab"&&Equal@@Length/@#&@*Split@*Characters

Thanks @MartinEnder for shortening it by 26 bytes :)
If input can be a list of characters instead of a string, 39 bytes is possible:
#&@@@#=={a,b}&&Equal@@Length/@#&@*Split

eg:
#&@@@#=={a,b}&&Equal@@Length/@#&@*Split@{a,b,a,b,a,b}

(*False*)

It's probably shortest with a recursive regex: #~StringMatchQ~RegularExpression@"(a(?1)?b)"&

@MartinEnder Ah yes - much better - I'll delete & let you post that, since it doesn't resemble my awful attemp in the slightest!

No, don't delete yours. A regex-less solution is still interesting. :)

JavaScript, 34 bytes
s=>(s=s.match`^a(.*)b$`[1])?f(s):1

In true automata fashion, this function returns 1 if it's true, and fails if it's not.

f=s=>(s=s.match`^a(.*)b$`[1])?f(s):1

let test_strings = ["ab", "aabb", "", "a", "abb", "abc", "abab", "abba"];
test_strings.map(s => {
try {console.log("f(\"" + s + "\") returned " + f(s));}
catch(e) {console.log("f(\"" + s + "\") threw " + e);}
});

Racket, 91 bytes
(λ(x)((λ(y)(equal?(append(make-list(- 1 y)#\a)(make-list y #\b))(cdr x)))(/(length x)2)))

Expects input in the form of a list of characters.  If you really need to put it in as a raw string, that adds 21 extra characters (for 112 bytes):
(λ(x)((λ(y)(equal?(append(make-list(- 1 y)#\a)(make-list y #\b))(cdr(string->list x))))(/(string-length x)2)))

An even longer (102 bytes with list input) way, but I think it's creative so I'm leaving it here:
(λ(x)(and(eqv?(/(length x)2)(length(member #\b x)))(eqv?(length(remove-duplicates(member #\b x)))1)))

Explanation to follow.

Excel, 55 bytes
=AND(A1<>"",A1=REPT("a",LEN(A1)/2)&REPT("b",LEN(A1)/2))

Test string in cell A1, formula above in any other cell. Generates a comparison string of the appropriate length and checks for a match. Shows TRUE or FALSE as appropriate.

PHP, 61 40 bytes
new approach inspired by Didz´ answer: regexp with a recursive pattern
<?=preg_match('#^(a(?1)?b)$#',$argv[1]);

P.S.: I see now that I am not the first one with this pattern. You never stop learning.

Josh´s C solution translated to PHP comes at the same size (with one byte lost in translation, one byte golfed for PHP with bitwise and, one byte golfed for C and PHP):
<?=strlen($s=$argv[1])==2*strspn($s,a)&$s[strrpos($s,a)+1]>a; (61 bytes)

My second own approach, a little longer: build a string with (input length / 2) of a, one of b and compare the concatenation to input:
<?=str_repeat(a,$n=strlen($s=$argv[1])/2).str_repeat(b,$n)==$s; (63 bytes)
Could save 3 bytes on that if I could use ($r=str_repeat) for a function call directly ... if.

all versions:

take the string as argument from cli
print 1 for true, nothing for false

testing

replace <?= with <?function f($s){return
remove =$argv[1] (or replace $argv[1] with $s)
append } and my test suite (below)
call in a web browser

function out($a){if(is_object($a)){foreach($a as$v)$r[]=$v;return'{'.implode(',',$r).'}';}if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';}
function test($x,$e,$y){static $h='

input	output	expected	ok?
';echo"$h
",out($x),'	',out($y),'	',out($e),'	',$e==$y?'Y':'N',"
";$h='';}
$cases=[
    1=>[ab,aabb,aaabbb,aaaabbbb,aaaaabbbbb,aaaaaabbbbbb],
    0=>['',a,b,aa,ba,bb,aaa,aab,aba,abb,baa,bab,bba,bbb,aaaa,aaab,aaba,
        abaa,abab,abba,abbb,baaa,baab,baba,babb,bbaa,bbab,bbba,bbbb]
];
foreach($cases as$e=>$a)foreach($a as$x)test($x,$e,f($x)|0);

Pyth, 7 bytes
.AanV_S

Try it online
How it works
      SQ     sorted input
     _       reverse
   nV   Q    vectorized not-equal with input
  a      Q   append input
.A           test whether all elements are truthy

Brainfuck, 77 bytes
,
[
  [
    >+[>+<-]<<
    ,[>->+<<-]
    >[<<]
    >
  ]
  >+[<<]
  >
  [
    >-[>+<-]<<
    ,
    [
      [>->+<<-]
      >[<<]
      <
    ]
    >>
  ]
  +>[<]
]
<.

Expects input without a trailing newline. Outputs \x00 for false and \x01 for true.
Try it online.
The idea is to increment n for initial a characters and decrement n for subsequent b characters and then check whether n is zero at the end, short-circuiting to print false if the input does not match /^a+b+$/. Since the input is guaranteed to match /^[ab]*$/, we can ignore the fact that ord('a') = 97 and just use ord('b') = ord('a') + 1 to check for /^a+b/.

Cubically, 109 98 70 60 bytes
+52/1+55~=7!6&(:7UR'UF'D2~=7)6>7?6&(:7D2FU'RU'~=7)6>7!6&!8%6

-11 bytes thanks to TehPers
-10 bytes thanks to new language feature
Try it online!
Prints 1 if the string matches L, otherwise prints nothing.
Explanation:
+52/1+55            Sets the notepad to 97 ('a')
        ~           takes input
         =7!6&      exits if input is not 'a'

(             )6    While the notepad is truthy
 :7                 Save the current character value
   UR'UF'D2         Perform a cube operation
           ~=7      Set notepad to true if next character is the same

>7?6&               Exit if next character is end of input (-1)

(             )6    While the notepad is truthy
 :7                 Save the current character
   D2FU'RU'         Reverse one iteration of the previous operation
            ~=7     Set notepad to true if next character is the same

>7!6&               Exit if next character is NOT end of input
!8%6                Print 1 if the cube is solved

The looping operation has been replaced with a new sequence with a period of 1260, which will still never give a false negative but now is guaranteed to work for inputs of less than 1260 characters.
I've replaced the previous check for solved cube with !8%6. 8 is a recently added pseudo-face which is always equal to "Is the cube solved?" so I can just branch on that directly.

Why not do -6>7?6& instead of -6>7!6{...}? Also, couldn't you replace -6+111=3!6& with -6+21=3!6&, -6+1111=4!6& with -6+22=4!6&, and -6+11111=5!6& with -6+32=5!6&? You checked those faces earlier in the program. Also, you can replace -6=0!6& with -6>0?6& and remove the next -6 because 0 isn't greater than 0. Rather than =#!6&-6..., try =#0?6&.... I'm also pretty sure you can remove one or two of those checks, but I'm not a mathematician. I had a solution similar to this in mind, but I didn't think to compare the notepad to the previous value. Nice job!

Also, you can remove the -6 in -6=0!6& because to exit the loop before it, the notepad must be 0.

Ruby, 17 bytes (16 + '-n' flag)
p~/^(a\g<1>?b)$/

Try it online!
The recursive regex solution ported to ruby.

Nearly 5 months later, decided to come back to my first answer here to see if I could golf it more. Here's the results!

Zsh, 28 bytes
eval ${${${1:?}//a/( }//b/)}

Just as I posted my 29 byte answer, I thought "what about if we handle the empty case specially?" Turns out, it's one byte shorter!
Try it online!
Successful cases: ( ( ( ... ( ( ))...))).
Unsuccessful cases:

Unmatched/uneven parens: obviously fails
/ba/ case: ( )( ) is a "parse error" in the eval, but gives unknown file attribute:  if run directly.
Empty case: ${1:?} handles exactly this.

Zsh, 29 bytes
eval \(${${1//a/(+}//b/+i)}\)

Try it online!
Same "eval matching delimiters" principle, but this time using math mode instead of parameter expansions:
eval \(${${1//a/(+}//b/+i)}\)
     \(                    \)   # literal ( )
         ${1//a/(+}             # replace 'a' with '(+'
       ${          //b/+i)}     # replace 'b' with '+i)'

A successful result looks like: ((+(+(...+(++i)+...i)+i)+i)), incrementing i to 1 and adding it repeatedly. This will result in a positive integer, which (( )) evaluates truthy.
An unsuccessful result looks like one of the following:

Uneven/unmatched parens (obviously fails)
/^b(a{n}b{n})?a$/ case: (+i)(...)(+) fails with "missing identifier after +"
Any other /ba/ case: (...)(...) errors in math mode
Empty case: () is an anonymous function with no body, and errors

Original answer:

Zsh, 35 bytes
eval '${'${${1//a/'${'}//b/'}'}'#}'

Try it online!
(More examples)
Inspired by xnor's post, this outputs via exit code. Zsh will happlily handle nested ${}s, but will err on ${${...}${...}} or unmatched braces.
There are two caveats which makes this longer:

We need the outer ${...}, since ${}${} is valid zsh.
We need a # at then end, which causes an error when the input is the empty string:

${${}#} is prefix removal, which is fine.
${#} evaluates to the number of parameters, which will be an integer and not a valid command.

Welcome to PPCG! Nice first answer

Curry (PAKCS), 24 bytes
f('a':s++"b")=s==""||f s

Try it online!
Returns True for truth, and nothing otherwise.

Thunno 2, 10 bytes
Ṡ=s`abdcạ&

Attempt This Online!
Explanation
Ṡ=s`abdcạ&  # Implicit input
Ṡ=          # Is the input sorted?
  s         # Swap so the input is back on top
   `ab      # Push the string "ab"
      dc    # Count the occurrences of "a" and "b"
        ạ   # Are they equal to each other?
         &  # Logical AND
            # Implicit output

Ruby, 33 bytes
Try it online
->s{s==?a*(l=s.size/2)+?b*l&&l>0}

Pyke, 10 bytes
le"ab"*Sq&

Try it here!
Or 9 bytes if null input isn't valid
le"ab"*Sq

Ruby, 31 bytes
Aw, that poor syntax highlighter :)
->s{s=~/^a+/&&$&.tr(?a,?b)==$'}

Does s begin with one or more a? Is also that bunch of as ($&) the same as the rest of the string ($') if we replace all those as with bs?
test here

Actually, 14 bytes
"[]""ab"(t≡#ÆY

This uses the same strategy as xnor's solution for the first part: transform the input into a nested iterable.
Try it online!
Explanation:
"[]""ab"(t≡#ÆY
"[]""ab"(t      translate "a" -> "[", "b" -> "]"
          ≡     eval (since this is evaluating a literal, it still works in the online interpreter) - leaves a list if the string is valid, else a string
           #    listify (does nothing to a list, makes a list of characters for a string)
            Æ   filter strings (take all string elements in the list - so an empty list if there are none)
             Y  boolean negate (an empty list is falsey and a non-empty list is truthy, so negation gets the correct value)

C#, 78 67 bytes
bool f(string s)=>Regex.IsMatch(s,"^(?'o'a)+(?'-o'b)+(?(o)(?!))$");

This implementation uses .NET Regex's "Balancing Group Definitions" to match the same number of 'a' and 'b' characters while ensuring that the input isn't an empty string by using the + quantifier.

Try it online! - current version

bool f(string s)=>Regex.IsMatch(s,"^(a)+(?<-1>b)+$(?(1)^)");: -7 bytes by golfing the regex

(s)=>Regex.IsMatch(s,"^(a)+(?<-1>b)+$(?(1)^)"): -14 bytes more (46 bytes) by using an anonymous function

Though I don't know if it's proper not to count the System.Text.RegularExpressions import in the byte count, if it's not included in your language name.

Python, 101 bytes
def q(s):
 a=len(s)/2
 for x in range(a):
  if s[x]!='a' or s[a+x]!='b' or a*2!=len(s):a=0
return a

Not the most efficient, had some trouble with 0 being even.  Could probably get it lower with python tricks.
Returns 0 if false, a positive integer if true. (which will be half len(s))

k (21 bytes)
Can probably be shorter
{|/0,(=).(#:'=x)"ab"}

Example
k){|/0,(=).(#:'=x)"ab"}""
0b
k){|/0,(=).(#:'=x)"ab"}"ab"
1b
k){|/0,(=).(#:'=x)"ab"}"aab"
0b

Gives the wrong answer for "abba"

Matlab, 67 chars
s=input('');l=num2str(length(s)/2);regexp(s,['^a{',l,'}b{',l,'}$'])

The regular expression searches for exactly half the input's length in as consecutively at the beginning of the input string, followed by exactly half of the input's length in bs consecutively right up to the end of the input string. It returns [] on a non-even-length input, empty strings, and non-Language-L strings and only returns 1 on strings that are part of Language L.

TI-Basic, 35 bytes
Zero is True; anything else is False.
Input Str1
1+.5length(Str1
inString(Str1,"a",Ans) or Ans≠inString(Str1,"b

Explanation
Input Str1                 Get string into Str1
1+.5length(Str1            Get number that is one more than half. For example, 8 gives 5.
inString(Str1,"a",Ans)     Yields zero if there is no instances of a in the second half
                               (using the number we just calculated as the start point for the search)
 or                        Both conditions need to be zero in order to output zero
Ans≠inString(Str1,"b       Yields zero if the first instance of b is the number we calculated earlier

I think you might be confused... parentheses don't have to be closed in TI-Basic. Thanks for the concern, though.

You're not using TI-Basic's notion of truthy/falsy here. How is that allowed?

I answered this a while ago, and it seems that we could specify which outputs indicated true or false. But, in accordance with your suggestion you could add not( to the beginning of the last line.

Ruby, 42 bytes
This is a simple solution, but unfortunately longer than many of the other Ruby solutions.
->s{s=~/^a+b+$/&&s.count(?a)==s.count(?b)}

Ungolfed:
def f(s)
  if s =~ /^a+b+$/ && s.count(?a) == s.count(?b)
    return true
  else
    return nil
  end
end

PHP bounty version, 31 bytes
for PHP 4.1, call php-cgi -f

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


text:
Semi-decide Post's Correspondence Problem
The Post's Correspondence Problem (PCP) gives you a list of pairs of strings, P_1 ... P_n. Your task is to find a k, and some sequence of k indices such that fst(P_i1) ... fst(P_ik) = snd(P_i1) ... snd(P_ik)
We're trying to find some sequence of the pairs where the word we build from the first part is equal to the word on the second part.
A solution can use any of the pairs any number of times, and in any order.
For example, if our pairs are (0,110), (11,1) and (001,100) , then one solution is the world 11001110, with the solution sequence of 2321:
11 001 11 0
1  100 1  110

Some will have no solution, such as (001, 01), (0001, 01).
Input:
An arbitrary number of words, separated by spaces.
Each word is of the format seq1,seq2 where each seq1 and seq2 are strings consisting only of 0 or 1, of arbitrary length.
Example: the above examples would have the following formats:
0,110 11,1 001,110

001,01 0001,01

Output:
If there is some sequence of the pairs which solves the PCP, output the word of the solution, followed by a space, followed by the sequence. The pairs are numbered starting at 1.
If there is no such sequence, run forever. (The problem is undecidable, so this will have to do).
Example output
11001110 2321

# second example never halts

Hint:
This is Turing Complete, so you're going to have to use some sort of infinite search.

The usual term is "recognize".

Python 3, 223 216 199 192 191 189 183 bytes
Thanks to @KarlKastor for pointing out that I could use count
from itertools import*
j=''.join
def f(x):
 for l in count(1):
  for i in product(x,repeat=l):
   *b,=zip(*i);c=j(b[0])
   if c==j(b[1]):print(c,j(str(x.index(k)+1)for k in i));return

A function that takes input of a tuple of pairs of strings x in the form ((seq1,seq2),(seq1,seq2)...) and prints the output to STDOUT in the same format as the test cases.
To continuously output solutions rather than just one solution, remove the return statement.
How it works
The function generates all l-length arrangements of the string pairs using product, with l being initialised at 1. This list is then unpacked and transposed using zip; this leaves a two-element list, where the first element contains all the first strings in the pairs, and the second all the second strings in the pairs. Each element is concatenated to a string using join; if these are the same, we have a hit and the string is printed to STDOUT. The sequence of pair indices is then generated by looking up each pair in the original arrangement using index; these indices are concatenated to a string, and also printed to STDOUT. If no solution exists for that l, l is incremented and the process repeated.
Try it on Ideone

was going to post an extremly similar solution in Python3, but you beat me to it

damn, posted mine because it was 3 bytes shorter, but then you updated yours. btw try if you can get it shorter by using for i in count() instead of while 1:i=len(x);i+=1, also why start counting at len(x)?

i wrote "i" instead of "l", but meant your "l"

@KarlKastor Of course! I had forgotten about count. As for starting at len(x), I'm not quite sure what I was thinking.

I shouldn't have helped you, now your bytecount is lower :p

@KarlKastor And lower again ;).

curse you, Bikinig the Viking

You can also use \x`instead ofstr(x)`. Or does this not work in Python 3? (I've given up modifying my version, because if i golf it any further it will just become yours)

@KarlKastor No, that doesn't work in Python 3.

Python 2, 220 215 203 199 195 193 187 bytes
from itertools import*
def f(p,o="".join):
 h=lambda s:o(x[s]for x in j)
 for i in count(1):
  for j in product(p,repeat=i):
   if h(0)==h(1):print h(0),o(`p.index(k)+1`for k in j);return

example use:
>>> f([("0","110"),("11","1"),("001","100")])
('11110', '221')

Pyth - 55 43 bytes
Msm@c@cz\ tvd\,H`G;.VZI>Z0B#=Z?qgb0gb1bZB;Z

Old version:
DgGH=TkV`G=+T@c@czdtvN\,H)RT;JZ.VZI>J0B#=J?qgb0gb1bJB;J

Explanation:
M                           #define a function g(G,H)
 s                          #join and return the following
  m             `G;         #for each char d in str(G):
     @cz\ tvd               #split input on " " and get the element at index int(d)-1
   @c        \,H            #split that on "," and get the element at index H
-----------------------------------------------------------------------------------

.VZ                  ;      #for b from 0 to infinity
        #             B     #try
         =Z?       bZ       #set var Z (which defaults to 0) to b if
            qgb0gb1         #g(b,0) is equal to g(b,1)
   I>Z0B                    #if Z>0, break
                       Z    #print Z

This program iterates from 0 to infinity. Each value is split digit by digit and that sequence is checked to see if it is valid. There is a try block so any sequences that go out of range are ignored, but considering how many sequences contain indexes that go out of bounds, this algorithm is painfully inefficient. But since when is code golf about efficiency?

Haskell, 260 253 243 230 Bytes
import Data.List
c=concat
x=concatMap
l p=x(\n->sequence$replicate n[0..length p -1])[1..]
i p=map(unzip.(map(p!!)))$l p
f p=x(show.(+1))(a l)++" "++(c$fst$a i)
 where a e=e p!!((\(Just x)->x)$findIndex(\x->c(fst x)==c(snd x))$i p)

use like: f([("0","110"),("11","1"),("001","110")])
This could probably be A LOT shorter, but what the hell...
-10 bytes thanks to @jmite
-13 by replacing fromJust with lambda

source: Stack Exchange

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

sort: votes


text:
How to weight loss easily?
In this question, we will only focus on losing weight by doing exercise, although there are still many ways to lose weight.
Different sports burn different amount of calories.
For example, playing billiards for an hour can burn 102 calories[1], while playing basketball for 15 minutes can already burn 119 calories [1], which make weight loss by playing basketball easier, at least from some perspectives.
The exact way to weigh the easiness is by dividing the amount of calories burnt by the time needed, which gives us the easiness index (EI).
For example, fencing for 15 minutes can burn 85 calories, which gets an EI of 85/15.
You will be given a list in this format:
[["fencing",15,85],["billiards",60,102],["basketball",15,119]]

or other format that you want.
Then, you will output the sports which have the highest EI.
TL;DR
Given a list of tuples [name,value1,value2] output the name where value2/value1 is the highest.
Constraints

You may not produce any real number that is not integer in the process.
You may not use any fraction built-in.

Specifications (Specs)

If there is more than one name that satisfy the result, you may output any non-empty subset of them or any element of them.
The name will match the regex /^[a-z]+$/, meaning that it will only consist of lowercase Latin standard alphabet.
The list will not be empty.

Testcase
Input:
[["fencing",15,85],["billiards",60,102],["basketball",15,119]]

Output:
basketball

References

http://calorielab.com/burned/

Do we get the list as a String, or an array/list?

@charredgrass As an array, as is the usual practice of this site.

Can we choose what order the [name,value1,value2] are given in?

Is it OK if dividing integers in our language produces a fractional type by default?

yes 2. fraction built-in

Isn't this do X without Y?

@MartinEnder Yes, this is an example of "do X without Y".

102 cal/h is virtually indistinguishable from your base metabolism

Do you mean "How to lose weight easily?" not "How to weight loss easily?"..

@Insane It's an inside joke.

@LeakyNun Right.. inside jokes on titles.. because the majority of people read it as bad grammar :P

"If there is more than one name that satisfy the result, you may output any subset of them." Does this mean I can return the empty set?

@acbabis but if there is just one name that satisfy the result, you can not. Good luck trying to save bytes with that special case

I was about to flag this as spam

Python 2, 51 bytes
lambda l:max((10**len(`l`)*a/b,s)for s,b,a in l)[1]

Does the obvious thing of finding the entry with the biggest ratio, but sidesteps the prohibition against floats by first multiplying the numerator by a huge input-dependent power of 10 before floor-dividing.
I'll prove this coefficient is big enough to make floor-division act the same difference as non-floor division.
Claim: If a1/b1 > a2/b2, then floor(Na1/b1) > floor(Na2/b2) for any N≥b1b2.
Proof: Note that a1/b1 - a2/b2 is a multiple of 1/b1b2, so a1/b1 - a2/b2 > 0 implies that

a1/b1 - a2/b2
≥ 1/b1b2

Then, multiplying both sides by N,

Na1/b1 - Na2/b2
≥ N/b1b2 ≥ 1

So, since Na1/b1 and Na2/b2 differ by at least 1, their respective floors are distinct. ∎
Now, note that the product b1b2 has digit length at most their total digit length, which is less than the string length of the input. Since the input is in base 10, its suffices to use 10 to the power of its length N=10**len(`l`) to produce a number with more digits than it, guaranteeing the condition.

Any chance e.g. 9 might work instead of 10?

@Lynn Unfortunately, it fails for huge inputs like [('y', 10**296+1, 1), ('x', 10**296, 1)].

JavaScript (ES6), 43 bytes
a=>a.sort(([p,q,r],[s,t,u])=>q*u-r*t)[0][0]

Or alternatively
a=>a.sort((v,w)=>v[1]*w[2]-v[2]*w[1])[0][0]

Sort is of course overkill for this, but reduce would take 46 bytes:
a=>a.reduce((v,w)=>v[1]*w[2]-v[2]*w[1]?v:w)[0]

If u take [p,q,name] u can save 4 bytesa=>a.sort(([q,r],[t,u])=>q*u-r*t)[0][2]

MATL, 8 bytes
pG/*&X<)

All computed numbers are integer values. First, the product of the denominators is computed (this is an integer). This product is divided by each denominator (which gives an integer too). Each result is then multiplied by the corresponding numerator. This gives an integer value proportional to the original fraction.
Input format is: numeric array with denominators, numeric array with numerators, cell array of strings with sport names:
[85, 102, 119]
[15, 60, 15]
{'fencing', 'billiards', 'basketball'}

If there are several minimizers the first one is output.
Try it online!
p     % Take first input. Compute the product of its entries
G/    % Divide by first input element-wise
*     % Take second input. Multiply by previous array element-wise
&X<   % Argmax
)     % Take third input. Index into it using previous result. Display

Brachylog, 42 bytes
:{bh.}a*g:?z:2aott.
[D:[S:I:J]]tt:D*:I/:S.

Try it online!
/ above is integer division because both J*D and I are integers (D is a multiple of I in fact).
Explanation

Main predicate: Input = [["string":mins:cals]:...]
:{bh.}a*                Multiply all mins in the Input together
        g:?z            Zip that number with the Input
            :2a         Apply predicate 2 to that zipped list
               ott.     Sort the list of lists on the values of the first element of
                          sublists, Output is the string of the last sublist

Predicate 1:
[D:[S:I:J]]             Input = [D:[S:I:J]]
           tt:D*        Multiply J by D
                :I/     Divide the result by I
                   :S.  Output = [That number:S]

Dyalog APL, 18 bytes
⎕⊃⍨(⊢⍳⌈/)⎕×(∧/÷⊢)⎕

Prompts for times, then for calories, then for activity names.
⎕ prompt (for times)
(∧/÷⊢) LCM ∧/ of the times divided by ÷ the times ⊢ (so no floats)
⎕× prompt (for calories) and multiply by them
(⊢⍳⌈/) in that ⊢, get the position ⍳ of the maximum value ⌈/
⎕⊃⍨ prompt (for activities), then pick the nth.
Example run:
      ⎕⊃⍨(⊢⍳⌈/)⎕×(∧/÷⊢)⎕
⎕:
      15 60 15
⎕:
      85 102 119
⎕:
      'fencing' 'billiards' 'basketball'
basketball

Retina, 64 62 bytes
Byte count assumes ISO 8859-1 encoding.
\d+
$*
%`\G1
0
1
:$_:
Ts`0p¶`0_`:.+?:
+`(0+) \1
@$1
O`
!`\w+$

Input is one sport per line, with the format value1 value2 name. Output is one of the maximal results (if there's a tie it will give the one with the largest value1 and if those are tied as well if will give the lexicographically larger name).
Note that this is super slow (for the exact same reasons as yesterday's Stack Exchange outage). To make it run in a reasonable amount of time, you can add a \b in front of the (0+) (which won't affect the way it processes the input at all but severely limits the backtracking of that regex). I've done that in the test link below.
Try it online!

Python 2, 55 54 bytes
lambda x:sorted(x,lambda(S,N,D),(s,n,d):N*d-n*D)[0][0]

Thanks to @xnor for golfing off 1 byte!
Test it on Ideone.

Nice! I forgot that sorted can take a two-input comparator function, I was going to hack that together.

Seems like it's shorter to unpack lambda(a,b,c),(d,e,f):b*f-c*e.

@xnor Neat! I didn't know you could do that.

Haskell 72 70 bytes
import Data.List
(n,(x,y))%(m,(a,b))=compare(x*b)$y*a
fst.minimumBy(%)

Usage :
main=putStr$(fst.minimumBy(%))[("fencing",(15,85)),("billiards",(60,102)),("basketball",(15,119))]

Mathematica, 46 bytes
Last/@MaximalBy[#,g=LCM@@First/@#;g#2/#&@@#&]&

The order of the tuples should be {value1,value2,name}. Returns the full set of all maximal results.
I work around the use of fractions by multiplying the numerator by the LCM of all value1s before the division.

Ruby, 72 bytes
e=0;while gets;n=$_.split;f=eval n[2]+"/"+n[1];m,e=n[0],f if f>e;end;p m

I really thought this would be shorter...
Input is taken from STDIN in the format of name time calories
Oh well, any help to shorten it is appreciated.

R, 42 40 bytes
function(v)v[which.max(v[,3]%/%v[,2]),1]

Takes input in the form of a data frame with column types of string (it also works with factors), numeric, numeric.

%/% is integer division.

This is my first submission, let me know if it's within the rules.
Edit: Turns out you don't need the braces to define a one-line function.

Might this give the wrong answer if two similar ratios divide to the same integer, e.g. 7/3,9/4?

My understanding is if they divide to the same integer, you can output any of them, this will output the first in data frame.

C++14, 89 bytes
Lambda function:
[](auto s,int*a,int*b,int l){int r=--l;while(l--)r=b[l]*a[r]>a[l]*b[r]?l:r;return s[r];};

Ungolfed:
[](auto s,int*a,int*b,int l)
{
  int r = --l;
  while(l--)
    r = b[l] * a[r] > a[l] * b[r] ? l : r;
  return s[r];
};

Usage:
#include <iostream>

int main()
{
  const char* s[] = {"fencing", "billiards", "basketball"};
  int a[] = {15,60,15};
  int b[] = {85,102,119};
  std::cout << [](auto s,int*a,int*b,int l){int r=--l;while(l--)r=b[l]*a[r]>a[l]*b[r]?l:r;return s[r];}(s,a,b,3);
}

Haskell, 46 bytes
s(n,(x,y))=(divMod y x,n)
g =snd.maximum.map s

EDIT: This solution doesn't work as pointed out by Damien this doesn't solve the problem. I'm searching a nice fix.

s(_,(x,y))=divMod y x is shorter

s(n,(x,y))=(divMod y x,n)
g=snd.maximum.map s too..

But this does not solve the problem as divMod a b < divMod c d is not equivalent to a/b < c/d. divMod 19 4 < divMod 55 12 but 19/4 > 55/12

Mmmh indeed my solution is quite poor… I'll think of nice fix, thanks !

VBA Excel, 109 bytes
Function A(B)
R=1
For I=2 To B.Rows.Count
If B(R,2)*B(I,3)>B(I,2)*B(R,3) Then R=I
Next
A=B(R,1)
End Function

Invoke in spreadsheet cell referencing a table of activities and parameters:

05AB1E, 6 7 bytes
P¹÷*ZQÏ

+1 byte to bugfix my divmod approach (see this comment on another answer) by porting @LuisMendo's MATL answer, so make sure to upvote him!
Input is similar as his answer: three separated lists, being an integer-list of denominators; an integer-list of nominators; and a string-list of names.
Try it online or verify some more test cases.
Explanation:
P       # Take the product of the (implicit) input-list of denominators
        #  i.e. [85,102,119] → 1031730
 ¹÷     # (Integer)-divide it by each of the denominators of the first input-list
        #  i.e. 1031730 / [85,102,119] → [12138,10115,8670]
   *    # Multiply each (at the same positions) by the (implicit) input-list of nominators
        #  i.e. [12138,10115,8670] * [15,60,15] → [182070,606900,130050]
    Z   # Get the maximum of this list (without popping the list itself)
        #  i.e. [182070,606900,130050] → [182070,606900,130050] and 606900
     Q  # Check which values are equal to this maximum
        #  i.e. [182070,606900,130050] and 606900 → [0,1,0]
      Ï # Only leave the strings of the (implicit) input-list of names at the truthy indices
        #  i.e. ["fencing","billiards","basketball"] and [0,1,0] → ["billiards"]
        # (after which the result is output implicitly)

PHP, 98 bytes
Used a simpler input format than the example, just like this:
fencing,15,85,billiards,60,102,basketball,15,119
$s=explode(",",$argn);for($x=0;$s[$x];$x+=3){if($y<$e=$s[$x+2]/$s[$x+1]){$y=$e;$z=$s[$x];}}echo$z;

Try it online!

8086 opcode, 24 bytes
31db 50ac f6e7 92ac f6e3 39d0 ad72 058b  1.P.......9..r..
5cfc 5ab2 58e2 ebc3                      \.Z.X...

org 100h
mov si, input
mov cx, 3
call f
mov dx, ax
mov ah, 9
int 0x21
ret
align 2
input:
db 15, 85
dw .fencing
db 60, 102
dw .billiards
db 15, 119
dw .basketball
.fencing db 'fencing$'
.billiards db 'billiards$'
.basketball db 'basketball$'
db 100h+2000-$ dup ? ; Easy to measure size
f:
; bx (record)
; dx (mul result 1)
; ax (result name, pushed)
; ax (mul result 2)
; cx (count)
; si (input array)
xor bx, bx
.L:
push ax
lodsb
mul bh ; nl*bh
xchg ax, dx
lodsb
mul bl ; nh*bl
cmp ax, dx
lodsw
jb .a
mov bx, [si-4]
pop dx
db 0xB2 ; Skip 1 byte
.a:
pop ax
loop .L
ret

db 0xB2 can be push ax

Java 8, 128 Bytes
String f(List<Object[]>l){return l.stream().max((x,y)->(int)x[2]*1000/(int)x[1]-(int)y[2]*1000/(int)y[1]).get()[0].toString();}

Clojure, 63 bytes
#((last(sort(fn[[x a b][y c d]](-(* b c)(* a d)))%))0)

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

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


text:
Draw the EU Estimated Sign
The specification of the "estimated" sign used by the European Union Directive (U+212e in Unicode, which you may not simply print for this challenge) is quite precise.

To copy some restrictions from this question: Render the symbol to file or screen using vector or raster graphics. If your output is rasterised, your image must have dimensions of 264 pixels × 240 pixels or more. Any other helping lines or length indicators must not be drawn.

Quite precise, but still a bit unclear. What exactly are the 0,085, 0,013, and 0,025 measuring? Is the 0,846 diagonal in the middle intended to pass through the epicenter of the ellipse formed by the outer 1 and 0,9?

Not the same symbol, but I think this is close enough to be considered a dup: http://codegolf.stackexchange.com/questions/26689/draw-the-%E2%82%AC-sign. I'm not using my dup hammer though.

@TimmyD 0,025 is the thickness of the cross bar, which is extends +/-0,0125 either side of the centre of the ellipse, rather than sitting on top of the centreline. (I inverted the symbol and checked.) 0,013 is the radius of the corner (it should be easy to find the centre of the corner circle). 0,085 is also the radius of the corner (a bit of help in finding the y coordinate of the corner circle would be nice.)

More interesting if you avoid using the letters 'E', 'n', 'g', 'l', 'a', 'd'...

VBA, 587 560 bytes
Sub S(a,b,c,d,e,f)
Set v=ActiveSheet.Shapes.AddShape(a,b,c,d,e)
v.Fill.ForeColor.RGB=f
v.Line.Visible=0
If a=5 Then v.Adjustments(1)=.5
End Sub
Sub U():p=91.5:w=-1
S 1,0,0,500,450,w
S 9,0,0,500,450,0
S 9,38.5,13.5,423,423,w
S 1,36,120,29,210,0
S 1,65,80,26.5,290,0
S 1,435,120,29,105,0
S 1,408.5,80,26.5,145,0
q=212.25:S 1,9,q,480,19,0
S 5,p,205.75,317,13,w
S 1,405,231.25,95,131.5,w
r=14.5:S 1,p,70.5,r,30,0
q=85:S 9,p,59.6,q,q,w
S 1,p,349.5,r,30,0
S 9,p,305.4,q,q,w
S 1,395,70.5,r,30,0
S 9,323.5,59.6,q,q,w
q=231.25:S 1,p,q,6.5,6.5,0
S 9,p,q,13,13,w
End Sub

Invoke macro U. Basically a lot of shape drawing. Shape 1 is a rectangle, 5 a rounded rectangle and 9 is an oval. Output is 500 wide by 450 high.

Edit: added the rounded rectangle (with adjustment to turn the ends into semicircles) to produce the radiused corners on top of the bar with one shape draw.

Excel lent - You sure did put a lot of work into that one! You can drop 2 bytes by changing Sub U() to Sub U

Actuallly, you can get this down to 535 bytes by making changing f to Optional f=0 and removing the 0 f calls, removing the space in a=5 Then, moving the subroutines to a worksheet codepane and removing the ActiveSheet. call (this means that U is then called as Sheet1.U) and removing the () in Sub U()

Haml + Sass, 20 + 722 = 742 bytes
I'm sure this could be golfed a lot more, but I'm happy enough with it. Demo on CodePen.
Note: Because of default margins, this needs a browser window at least 1,000-some pixels wide.
Haml
#u
#v
 #w
 #x
 #y
#z

Sass
$w: 1000px
$h: 900px
$a: 183px
$b: 25px
$p: 85px
$q: 13px
$d: 846px
$e: $w - 2*$a
$f: 143px
$s: 50%
$t: $p/5.5
=d($w:$w,$h:$h)
 width: $w
 height: $h
=m($c)
 background-color: $c
=k
 +m(#000)
 position: absolute
 content: ''
=l
 +k
 +m(#fff)
=o($o:$p)
 +d($o,$p)
=r($a)
 border-radius: $a
*
 +k
html,body
 +l
 position: relative
#u
 +d
 clip-path: ellipse($s $s)
#v
 +d($e)
 left: $a
 clip-path: circle(($d/2) at $s $s)
#v::before,#v::after
 +l
 +d($e,($h -$b)/2)
 +r($q)
#v::after
 bottom: 0
#w,#x
 +o($t)
 top: $f
#w::before,#x::before,#y::before
 +l
 +o
 +r($s 0)
#x,#x::before
 right: 0
#x::before
 +r(0 $s 0 0)
#y
 +o($t)
 bottom: $f
 z-index: 9
#y::before
 +r(0 0 0 $s)
#z
 +l
 +d($s,267px)
 top: ($h+$b)/2
 right: 0

GLSL + shadertoy.com, 349 345 344 bytes
#define F float
void mainImage(out vec4 R,vec2 C){F S=min(iResolution.x,iResolution.y/0.9);vec2 p=C/vec2(0.5,0.45)/S-1.;F A=0.94-length(p*vec2(1.22,1));F H=min(min(-p.y-0.025,p.y+0.551),p.x);F B=max(length(p)-1.,min(abs(p.y)-0.025,max(A,H)));F D=max(min(p.x,-p.y),max(-A,0.634-abs(p.x)));R=vec4(vec3(max(H,min(B*D*64.-0.01,min(B,D)))*S/3.),1);}

Can be tested by pasting the code on this page: https://www.shadertoy.com/new
Output (when the screen size is 1440*900):

Not sure about your corners at the ends of the central bar there, they don't look quite right.

Maybe they should have a little different "size", I didn't really understand what size they should be, so approximated it with eyes

They should be circular arcs with a radius of 0.013 (x the full width of the figure).

PostScript, 280 140 bytes
Now smaller, with binary tokens and less precision!
00000000: 5b28 5b29 7b31 3339 9205 8881 3588 0035  [([){139....5..5
00000010: 2035 9207 887f 3588 7f88 2835 9207 9242   5....5...(5...B
00000020: 747d 285d 297b 885d 3938 8822 3088 2d92  t}(]){.]98."0.-.
00000030: 0588 0c30 9285 9242 7d2f 747b 3188 ff92  ...0...B}/t{1...
00000040: 8b7d 3e3e 920d 8864 3930 92ad 387b 307d  .}>>...d90..8{0}
00000050: 9283 880a 3992 8b88 0a30 8768 0192 0592  ....9....0.h....
00000060: 422e 3035 202e 3035 3592 8b31 9296 87a9  B.05 .055..1....
00000070: 0034 315b 3587 4001 8869 9280 87a9 0034  .41[5.@..i.....4
00000080: 5b92 965d 88ff 3192 8b5d 745d            [..]..1..]t]

Before being tokenized (255 bytes):
[([){139 arc -127 5 0 5 5 arct 127 5 127 40 5 arct fill t}(]){93 98 34 0 45 arc 12 0 rlineto fill}/t{1 -1 scale}>>begin
100 90 translate
8{0}repeat
10 9 scale
10 0 360 arc fill
.05 .055 scale
1 setgray
169 41[5 320 105 rectfill
169 4[setgray]-1 1 scale]t]

Step-by-step:

Final output:

(Gray background is from Preview.app and not part of actual output.)

C (gcc), 251 248 bytes
-3 bytes thanks to @ceilingcat
#define q(x,y)(x)*(x)+(y)*(y)
#define A abs
main(i,j){puts("P5 264 240 1");for(i=-121;i++<119;)for(j=-133;j++<131;)putchar(((q(i,j*.9)>'8?'|q(i,j)<12471&A(j)<84)&q(A(i)-72,A(j)-81)>39|q(A(i)-65,A(j)-61)<504)&A(i)>3&(A(j)-83||A(i)-4)|j>0&i>3&i<73);}

Try it online!