We all know that if you google the word "google" it will break the internet.

Your task is to create a function that accepts one string and returns its length, in the fewest possible Unicode characters.

However, if the given string is google (lowercase), it will cause an error.

For example, g('bing') will return 4 but g('google') will cause an error.

Please provide an example of usage, and the error if possible.

## The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

## Language Name, N bytes


where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes


If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes


You can also make the language name a link which will then show up in the snippet:

## [><>](https://esolangs.org/wiki/Fish), 121 bytes


/* Configuration */

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

/* App */

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

}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(a) {
});
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

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

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

function process() {
var valid = [];

var body = a.body;
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});

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

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;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

var lang = a.language;
lang = jQuery('<a>'+lang+'</a>').text();

languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
});

var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);

langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) 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)
language = jQuery(language);
jQuery("#languages").append(language);
}

}
body {
text-align: left !important;
display: block !important;
}

width: 290px;
float: left;
}

#language-list {
width: 500px;
float: left;
}

font-weight: bold;
}

table td {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<tr><td>Language</td><td>User</td><td>Score</td></tr>
<tbody id="languages">

</tbody>
</table>
</div>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>

</tbody>
</table>
</div>
<table style="display: none">
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
</tbody>
</table>

• @Geobits That is simply a test to see if I will google Google, which I will not. :D – rybo111 Sep 28 '15 at 16:33
• Does the function need to be case sensitive? Should it throw given 'gOOgle'? – AXMIM Sep 30 '15 at 22:07
• When I type google into google (the search bar on chrome), a message came up asking if I wanted to go to google. (Now that it is a tld, this makes sense i.e. com.google works). I clicked it and got a dns lookup error. Internet:broken! – Craig Oct 1 '15 at 4:18
• I'm voting to reopen this. I have seen no questions about what constitutes an error for this challenge and it already has 154 answers so I don't think it's fair to change the spec. This may not be an example of a good question but it's clear enough. If an answer really comes down to whether or not a certain output is an error it probably just won't get as many upvotes, anyway. – Poke Aug 1 '18 at 19:52

# TI 89 BASIC, 34 bytes

I did this in TI 89 for fun. There has got to be a more optimized method, but this is the best I could come up with for the moment.

f(x)


Basically abuses the fact that a string divided by itself becomes 1.

0 is necessary to remove the string from the calculation otherwise you would return ("fun" + 3) which i don't think is compliant to the rules.

• Alright, wasn't sure if I could post multiple answers to a solution @lirtosiast , thanks! – STDQ Mar 26 '16 at 20:20

## Hoon, 32 bytes

|*
a/*
?<
(lent a)


Uses a wet gate to avoid having to specify a/tape instead of a/*, assert that a doesn't equal "google" or panic, return the length of the tape.

> %.  "abc"
|*
a/*
?<
(lent a)
3
|*
a/*
?<
(lent a)
ford: build failed ~[/g/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/use/dojo/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/inn/hand /g/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/use/hood/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/out/dojo/drum/phat/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/dojo /d //term/1]

• Um... is that supposed to link to urbit? – Destructible Lemon Nov 20 '16 at 9:55
• @DestructibleWatermelon Yup. Urbit provides the compiler/interpreter for the Hoon language. – RenderSettings Nov 21 '16 at 4:00

# Tellurium, 13 bytes

This language is newer than the question, so non-competing I guess.

i?google|d]L^


This program gets input using i, and checks if the input is "google". If it is, it tries dividing "google" by zero (d) well, that doesn't work (duh) so it throws an error.

If the input isn't google, it outputs the length of the selected cell's value (which is the input) using L^.

## AWK, 44 bytes

func f(x){return x=="google"?f(x):length(x)}


Example usages:

awk 'func f(x){return x=="google"?f(x):length(x)}{print f($0)}' <<< "non-google string" awk 'func f(x){return x=="google"?f(x):length(x)}{print f($0)}' <<< "google"


Print: 17 and Segmentation fault (core dumped) respectively. The second one may cause your computer to run out of memory before it segfaults if you don't have oodles of RAM.

I find Segmentation fault errors to be a bit more broken than divide by zero since they don't even say where the problem is.

Something that looks more interesting would be:

func f(x){if(x=="google"){printf x;return f(x)}return length(x)}


This would print googlegooglegooglegoogle.... wrapping around the screen until it finally produces the seg. fault, but it's not as 'golfy'

NB. Yeah, I'm a bit late to the party, but nobody had an AWK answer yet. :)

• +1 for "Segmentation fault (core dumped)" -- my favourite error message – cat Mar 25 '16 at 15:46
• It's my favorite message, too... if I'm not the one that has to debug it. :p – Robert Benson Mar 25 '16 at 16:04
• On my 64-bit Ubuntu 16.04 with GAWK 4.1.3, the second one doesn't segfault but just eats all my memory until one of three things happens. A) the oom-killer kills it and says Killed, B) my window manager crashes or C) my computer overheats and switches off. Thus, I am adding a note to your answer that this answer may be harmful on machines which have a big stack. – cat Jun 28 '16 at 13:34
• Aha! That's funny. It is not that your machine has so little memory space that AWK gives up and segfaults immediately, it's that you have so much memory that AWK doesn't cause the kernel to kill it but instead tries to address so much memory that its virtual machine eventually segfaults. I only have a paltry 6 GB of RAM :P – cat Jun 28 '16 at 16:32
• It's not wrong at all, I think recursing forever and possibly forcing a shutdown is a perfectly acceptable error – cat Jun 28 '16 at 16:52

# PowerShell, 36 35 Bytes

param($a)$a.length/($a-cne'google')  This blatantly abuses PowerShell's dynamic casting and uses xnor's trick for dividing by zero. In PowerShell, this is a terminating error and halts execution tossing a most excellently-verbose error (the error, at 242 characters, is over 6.5x the size of the function itself) Attempted to divide by zero. At line:1 char:11 + param($a);$a.length/($a-cne'google')
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException


Saved a byte thanks to ConnorLSW

• you can use param($a)$a.length/($a-cne'google') to skip using the the !, saving one byte. – colsw Nov 29 '16 at 10:57 • @ConnorLSW Indeed. Thanks. – AdmBorkBork Nov 29 '16 at 15:54 # PHP, 48 bytes eval((google==$s=$argv[1])."echo strlen(\$s);");


php -r '<code>' google -->

Parse error: syntax error, unexpected 'echo' (T_ECHO) [...] in eval()'d code on line 1

54 bytes for a function:

function g($s){eval((google==$s).'echo strlen($s);');}  # JavaScript, 25 bytes p=>p=='google'?_:p.length  • “However, if the given string is google (lowercase), it will cause an error.” – Will this? – manatwork Nov 29 '16 at 15:15 • Now it matches the challenge's requirement. Sadly the generic expectation is the solutions to be either full programs or functions. In both cases the input and output has to be handle either explicitly by the code or implicitly by the interpreter. So you can not assume your code will find data in some global variable. – manatwork Nov 29 '16 at 15:38 • You can make this valid in one of two ways: 1. Make it into a full program with input and output: g=prompt();if(g!='google')alert(g.length);else throw 0 2. Make it into a function: function(g){if(g!='google')return g.length;else throw 0} – ETHproductions Nov 29 '16 at 16:44 • Also, you don't have to explicitly throw an error; calling some undefined variable, such as _, will do the trick. – ETHproductions Nov 29 '16 at 16:44 ## PHP, 56 bytes function google($i){echo strlen($i)/(__FUNCTION__!=$i);}


Yes, it's a bit long, but I feel this is really in the spirit of the question. You really mustn't google google when google is the actual function's name.

The constant __FUNCTION__ holds the name of the function, which in this case is google. The rest of the functiondisplays the length of the input $i divided by 1 if $i is not google, or by 0 if it is. The latter throws an error.

Try it at Repl.it!

# Pyth - 15 bytes

?qz"google"'0lz


My favorite part of this is how I error. I use the ' function which takes a string, but pass 0, which is not a string.

## Wd, 10 9 bytes

This is a full program but is technically also a function.

*↔XÑ║╜▄]ÿ


## Explanation

Decompressed:

-Fl'InakS/


After string decompression:

google"nakS/

google"n     # Does the input *not* equal to "google"?
ak   # Find the length of the input
S/ # Divide the length of the input by the above condition


## CoffeeScript, 36 bytes

f=(x)->throw 0if'google'==x;x.length


# Emacs Lisp, 43 bytes

(lambda(s)(if(equal s"google")*(length s)))


Throws the error (void-variable *) for any string that equals google.

• @FryAmTheEggman I'm sorry, I just wrote the explanation wrong, the code is correct. – nanny Sep 28 '15 at 18:55

## STATA, 44 bytes

pr de a
if"google"==0' f
di length(0')
end


prints "unrecognized command: f" when input is "google"

# Perl5, 48 bytes

sub google{map{eval,-7+length}qq~&{"::$_[0]"}~}  google("google") and google will google("google"). Try it: perl -e 'sub google{map{eval,-7+length}qq~&{"::$_[0]"}~} print google @ARGV' google


## 47 bytes

The following is one char shorter, but more fiddly on the command line:

sub google{map{eval,-6+length}qq~&{"'$_[0]"}~}  # F#, 33 Characters function"google"->0/0|s->s.Length  When "google" is provided as input, it produces a DevideByZeroException. Usage: let g = function"google"->0/0|s->s.Length g "bing" // 4 g "google" // DivideByZeroException  # Java 1.8, 33 bytes (s)->s.length()/(s=="google"?0:1)  ## Explanation The lambda takes a String named s, finds the length, and if it isn't "google", divides it by one, otherwise dividing it by zero and causing an Exception. ## Usage Note that java.util.function.Function has to be imported. Function<String, Integer> f = (s)->s.length()/(s=="google"?0:1); //Assign function to variable //Note that java type inferencing automatically handles the String type System.out.println(f.apply("elgoog")); //Prints 6 System.out.println(f.apply("google")); //ArithmeticException: Divide by zero  • As far as I know, required imports need to be counted in the score, so your full code would be the import and the function. – Alex A. Sep 29 '15 at 15:53 • @AlexA. The thing with Java is that lambdas are weird- the question only asked for a function, and the lambda is a function. However, Java needs to squeeze the function into a functional interface with the same method signature (accepts string, returns int), and the Java.util.function.Function interface fits the bill. However, the full function is provided. (Also see codegolf.stackexchange.com/a/58981/41505) – Daniel M. Sep 29 '15 at 16:31 • You are going to have to change == to .equals unless I'm missing something with java 8 – jlars62 Oct 2 '15 at 16:55 • It worked for me using the provided implementation. It may be a subtle difference between String objects and literals, but it works for me – Daniel M. Oct 2 '15 at 17:08 # Lua, 47 bytes print(assert(arg[1]~="google")and arg[1]:len())  Throws "assertion failed" if it's "google" # golflua, 25 characters \g(s)?s=="google"e""$~#s$ Sample run: bash-4.3$ golflua -e '\g(s)?s=="google"e""$~#s$ w(g("google"))'
golflua: (command line):1:
stack traceback:
[C]: in function 'e'
(command line):1: in function 'g'
(command line):1: in main chunk
[C]: in ?

bash-4.3$golflua -e '\g(s)?s=="google"e""$~#s$w(g("yahoo"))' 5  # PHP, 41 bytes Because the division by zero is overused in the already existing answers, I tried to come up with something else (sacrificing 3 bytes): <?=strlen($x=$argv[1])+log($x!="google");


It's not a function (the task explicitly asks to write a function) but it can be invoked from the command line in a functional manner:

$echo '<?=strlen($x=$argv[1])+log($x!="google");' | php -- bing
4

$echo '<?=strlen($x=$argv[1])+log($x!="google");' | php -- google
-INF


It doesn't produce an error when the argument is google but it doesn't display the length of the string google either. However it displays -INF (i.e. minus infinity) and this value can be considered an error for a function that returns a length (which, by definition, is a count, i.e. a non-negative number).

<?=strlen($x=$argv[1])/($x!="google");  It can be invoked in the same way as above. When the argument is google it displays a PHP warning. • You get a +1 from me for the division-by-zero, clever! But a -1 for not making it a function as the topic states :) – Martijn Sep 29 '15 at 12:53 • -2 bytes: The quotation marks are unnecessary. – Titus Nov 29 '16 at 15:48 # Clojure - 41 40 bytes (defn g[s](if(= s"google")(g)(count s)))  Attempts to call itself with zero arguments for the input "google". > (g "bing") 4 > (g "google") clojure.lang.ArityException: Wrong number of args (0) passed to: sandbox10419$g


# Swift, 71 Bytes

Short but lame:

print({assert($0 != "google");return$0.characters.count}(readLine()!))


Longer (75) but not lame:

print({{0/$0}($0.hash&-0x20f4f91ecf8d43)^$0.characters.count}(readLine()!))  The second one doesn't use any String literal. Works by subtracting the hash value of the input string by the "google" hashValue. Then it divides 0 by this value, resulting in a runtime error when it's 0 (0/0 = undef.) but in all other cases the result is 0 (0/x = 0). This result gets XOR'd by the character count in the String. # Hassium, 52 Bytes func g(s){if(s=="google")throw("");return s.length;}  Run and see expanded here • func g(s)return(s == "google")?throw():s.length; is a bit shorter. – Dennis Oct 1 '15 at 5:42 • @Dennis Actually, it is 32 bits shorter. – Ismael Miguel Oct 5 '15 at 2:17 # Haskell, 24 characters g n|n/="google"=length n  "Unexhaustive patterns" if you pass it "google". # C - 72 characters g(char*s){char*p=s;for(;*p=="google"[p-s];p++);for(;*p;p++);return p-s;}  output: g("test") # 4 g("googles") # 7 g("google") # Segmentation fault (core dumped)  This solution is pretty straightforward, no tricky bit manipulation (but also no library functions): match the string google in the first loop, and if there are still characters left continue to the end of the string. Return the difference between the pointers as the length. The bug: given the string "google" the first loop does not terminate, causing it to overrun and dereference memory locations until it segfaults. It also has a bonus bug: if you feed it the string "google\0" it succeeds but returns the wrong length. # JS, 48 bytes An improvement over Beta Decay's JS: function f(g){g=="google"?g.s.s:alert(g.length)}  The original for reference: function f(g){if(g=="google")throw 1;alert(g.length)}  # Burlesque, 25 bytes J"google"!={L[}j{vvg_}jie  Code can be run at Anarchy Golf checker. Click 'use form' choose 'burlesque', copy/paste code into the form, and input goes under it. Run. • You can shorten {L[} to qL[. q is a syntax prefix as a shortcut for Blocks that only contain one value. – mroman Nov 15 '18 at 12:36 XPath 2.0 (if you treat an XPath expression as a function with the context item as its argument): Simple solution: if (.='google') then error() else string-length()  If you treat returning an empty sequence as an error, then string-length(.[.!='google'])  ## bash, 5551 34 bytes Thanks @manatwork! [ "$1" != google ]&&echo ${#1}||0  It prints command not found if $1 is google.

• Shorter? [ "$1" != google ]&&echo${#1}||0 – manatwork Sep 30 '15 at 9:16
• @manatwork Shorter & beautiful! – Tarod Sep 30 '15 at 10:30

## CoffeeScript, 32 bytes

g=(s)->(s if s!='google').length


To call:

g('bing') # returns 4


The expression (s if s!='google') evaluates to undefined if the value of the argument s is google, otherwise it gives the argument itself. In the former case, JavaScript throws an error when attempting to access a property of undefined.

## PowerShell, 42 bytes

function g($x){$x.Length/(\$x-ne'google')}