| Bytes | Lang | Time | Link |
|---|---|---|---|
| 026 | JavaScript V8 | 250427T104246Z | Steve Be |
| 037 | Swift 6 | 250426T204455Z | macOSist |
| 046 | Tcl | 170110T203357Z | sergiol |
| 049 | C gcc | 240523T130235Z | None1 |
| 014 | Uiua 0.11.0 | 240523T160923Z | RomanPro |
| 123 | Acc!! | 240522T051510Z | engineer |
| 008 | Vyxal | 230923T020113Z | ffseq |
| nan | TypeScript's Type System | 230920T030922Z | noodle p |
| 014 | APL | 150929T034734Z | marinus |
| 102 | GNU sed | 230919T124224Z | Philippo |
| 014 | Japt | 151126T061318Z | noisyass |
| 008 | 05AB1E | 170206T021118Z | Oliver N |
| 010 | 05AB1E | 160325T134704Z | Adnan |
| 030 | Python 3 | 210608T141147Z | KinuTheD |
| 034 | Red | 210604T160349Z | 9214 |
| 046 | Red | 210602T053332Z | wasif |
| 017 | Knight | 210524T042054Z | EasyasPi |
| 018 | Zsh | 210220T165729Z | pxeger |
| 047 | VBScript | 210410T061631Z | wasif |
| 008 | 05AB1E | 210218T222624Z | Makonede |
| 007 | Vyxal | 210222T020033Z | lyxal |
| 035 | Python 3.8 prerelease | 210221T170421Z | Gotoro |
| 053 | Whispers v1 | 210222T004847Z | Michael |
| 025 | Julia | 210221T174504Z | MarcMush |
| 046 | Racket | 210221T144728Z | MLavrent |
| 4744 | Clojure | 210220T200604Z | Satoshi |
| 035 | Lua | 200821T101943Z | val - di |
| 041 | JavaScript V8 | 200521T113753Z | Yaroslav |
| 109 | W d | 200102T102739Z | user8505 |
| 029 | Python 2 | 150928T163817Z | xnor |
| 016 | Keg | 200103T054919Z | lyxal |
| 012 | Brachylog | 190301T014331Z | Unrelate |
| 046 | GameMaker Language | 181007T125747Z | kepe |
| 009 | Stax | 180308T214535Z | Weijun Z |
| 038 | SmileBASIC | 170124T183710Z | 12Me21 |
| 035 | C | 170529T163747Z | MD XF |
| 050 | Common Lisp | 171127T221750Z | Renzo |
| 015 | Pyth | 171127T204623Z | Tornado5 |
| nan | 171126T092237Z | iBug | |
| 019 | Aceto | 171125T224945Z | qqq |
| 052 | Excel VBA | 170205T180222Z | Taylor R |
| 029 | Ruby | 150928T175510Z | daniero |
| 036 | MATLAB | 150928T175731Z | rayryeng |
| 010 | 05AB1E | 171017T182241Z | Magic Oc |
| 010 | Jelly | 171017T180741Z | caird co |
| 033 | Mathematica | 170918T213700Z | totallyh |
| 021 | shortC | 170529T164433Z | MD XF |
| 018 | Syms | 170529T232017Z | Calculat |
| 137 | GNU sed | 170211T085723Z | seshouma |
| nan | Ruby | 170124T235122Z | Value In |
| 068 | Edited processing JS | 170124T221650Z | user6318 |
| 056 | PHP | 170124T185002Z | steenber |
| 014 | Japt | 170110T200415Z | Oliver |
| 025 | JavaScript | 161129T150447Z | Oliver |
| 037 | Java | 160610T192554Z | user8397 |
| 033 | Clojure | 161129T161146Z | Carcigen |
| 048 | PHP | 161129T160850Z | Titus |
| 035 | PowerShell | 150928T183336Z | AdmBorkB |
| 019 | Perl 6 | 150929T132742Z | null |
| 026 | Ruby | 161120T222105Z | user344 |
| 046 | Python 2 | 161101T042124Z | James Mu |
| 029 | Perl | 150928T202359Z | Jarmex |
| 044 | AWK | 160325T140228Z | Robert B |
| 077 | C++ | 160610T155912Z | user5420 |
| 047 | Python | 151007T133902Z | m654 |
| 016 | Scratch | 160524T145435Z | weatherm |
| 013 | Tellurium | 160524T132005Z | m654 |
| 063 | Octave | 150928T185942Z | ಠ_ಠ |
| 012 | Pyth | 160426T201810Z | penalosa |
| 032 | Hoon | 160426T001847Z | RenderSe |
| 016 | Molecule v5.6+ | 160425T203026Z | user4701 |
| 021 | TI83 Basic | 160329T192306Z | Timtech |
| 030 | Python 3 | 150928T210300Z | Nick T |
| 034 | TI 89 BASIC | 160325T200240Z | STDQ |
| 041 | Rust | 160326T202412Z | STDQ |
| 042 | C++14 | 160326T202201Z | STDQ |
| 019 | Fuzzy Octo Guacamole | 160326T013923Z | Riker |
| 2624 | Julia | 160325T202041Z | M L |
| 049 | Factor | 160325T154506Z | cat |
| 020 | Gogh | 160326T033853Z | Zach Gat |
| 023 | Mathcad | 160325T130604Z | Stuart B |
| 039 | jq | 150928T183355Z | manatwor |
| 042 | Lua | 160130T225115Z | QuertyKe |
| 018 | Milky Way 1.0.0 | 151202T074527Z | Zach Gat |
| 092 | Go | 151121T015603Z | cat |
| 096 | Java | 151204T174207Z | Ashwin G |
| 029 | Ruby | 151126T152440Z | Vasu Ada |
| 019 | PARI/GP | 150929T031412Z | alephalp |
| 063 | MS TSQL | 151126T135918Z | Steve Ma |
| 060 | Game Maker Language | 151121T222826Z | Timtech |
| 110 | ಠ_ಠ | 151123T014548Z | Mama Fun |
| 1521 | 𝔼𝕊𝕄𝕚𝕟 | 151121T035728Z | Mama Fun |
| 029 | Zsh and bc | 151121T003448Z | Adam Kat |
| 017 | O | 151117T021201Z | jado |
| 015 | TIBASIC | 150928T181230Z | Conor O& |
| 118 | Windows Batch | 150930T012656Z | Shane Sm |
| 031 | Perl | 150930T174309Z | ASCIIThe |
| 034 | Powershell 34 Bytes | 151007T134052Z | Jonathan |
| 042 | OCaml | 150929T225256Z | Édo |
| 043 | Clojure | 151006T152340Z | Bob Jarv |
| 025 | JavaScript | 150929T080505Z | GeoffWil |
| 170 | Rust | 151006T080153Z | Liam |
| 081 | PHP 5.4 | 150928T200211Z | Dom Hast |
| 018 | J | 151005T213736Z | Alex Shr |
| 041 | Ruby | 151005T162134Z | Rocko |
| 047 | ><> | 151005T121850Z | Sok |
| 059 | Go | 150930T093708Z | user4556 |
| 032 | Groovy | 151005T102038Z | codeporn |
| 059 | Befunge93 | 151004T201133Z | El'e |
| 075 | AHK | 151003T225658Z | downrep_ |
| 025 | JavaScript ES6 | 150928T182841Z | Jonathan |
| 013 | Pyth | 150928T172625Z | Dennis |
| 043 | C# | 150928T192840Z | DLeh |
| 108 | ><> | 150928T214247Z | DanTheMa |
| 050 | Matlab | 150928T182428Z | Luis Men |
| 047 | C++14 | 151001T054909Z | sweerpot |
| 016 | CJam | 150928T170945Z | Dennis |
| 087 | TSQL 2012 | 151001T005020Z | AXMIM |
| 081 | C++ | 150930T203441Z | MegaTom |
| 016 | Stuck | 150930T181453Z | Kade |
| 030 | ECMA6 | 150930T181218Z | SparkX12 |
| 048 | C | 150929T203920Z | AShelly |
| 060 | Powershell | 150930T171415Z | Erik |
| 047 | JavaScript | 150928T174445Z | Beta Dec |
| 042 | PowerShell | 150930T155725Z | Sean |
| 032 | CoffeeScript | 150930T044333Z | Bungle |
| 029 | Scala | 150930T094806Z | Ben |
| 034 | bash | 150929T215633Z | Tarod |
| 020 | O | 150930T094719Z | manatwor |
| 051 | C# 4.0 | 150930T090716Z | peter sa |
| 046 | PHP error via a warning | 150929T125242Z | Martijn |
| nan | 150930T084619Z | Michael | |
| 025 | Burlesque | 150930T064241Z | TellsTog |
| 016 | GolfScript | 150928T215547Z | p.s.w.g |
| 048 | JS | 150930T023706Z | djechlin |
| 072 | C | 150929T234655Z | Alcamtar |
| 033 | bash + coreutils | 150929T212029Z | Ben |
| 063 | C | 150929T212005Z | Braden B |
| 024 | Haskell | 150929T205505Z | Ludwik |
| 025 | Javascript ES6 | 150929T023631Z | Generic |
| 048 | Scala | 150929T203503Z | ekrich |
| nan | C++11 | 150928T173926Z | Zereges |
| 048 | Common Lisp | 150928T190630Z | jqkul |
| 052 | Hassium | 150929T173301Z | Jacob Mi |
| 4049 | PHP 5.4+ | 150929T111043Z | Ismael M |
| 031 | rs | 150929T140523Z | kirbyfan |
| 071 | Swift | 150929T135629Z | Kametrix |
| 040 | Clojure | 150929T112708Z | cfx |
| 041 | PHP | 150929T113757Z | axiac |
| 032 | Prolog – | 150929T104412Z | Kijewski |
| 025 | golflua | 150929T073006Z | manatwor |
| 752 | Java 7 52 Bytes | 150929T032328Z | Akash Th |
| 017 | APL | 150929T030043Z | Alex A. |
| 047 | Lua | 150929T031915Z | Trebuche |
| 033 | Java 1.8 | 150929T023109Z | Daniel M |
| 055 | ><> | 150929T012739Z | cole |
| 024 | Haskell | 150928T232919Z | chs |
| 023 | Excel | 150928T223337Z | Hand-E-F |
| 033 | F# | 150928T212144Z | p.s.w.g |
| 048 | Perl5 | 150928T205005Z | user5288 |
| 042 | Lua | 150928T200830Z | Nico A |
| 046 | R | 150928T191956Z | syntonic |
| 044 | STATA | 150928T185702Z | bmarks |
| 043 | Emacs Lisp | 150928T183610Z | nanny |
| 026 | Ruby | 150928T174124Z | Borsunho |
| 065 | C# .NET | 150928T185122Z | Salah Al |
| 043 | CoffeeScript | 150928T181440Z | Bojidar |
| 036 | CoffeeScript | 150928T175637Z | rink.att |
| 035 | Python 3 | 150928T164733Z | Zach Gat |
| 028 | MUMPS | 150928T163550Z | senshin |
| 030 | Haskell | 150928T163542Z | C. Quill |
Swift 6, 37 bytes
let s={[$0.count][$0=="google" ?1:0]}
Pretty simple. If the argument is "google", crashes with an out-of-bounds index error; otherwise, returns the argument's length.
C (gcc), 49 bytes
#define f(x)""[!strcmp(x,"google")<<31]+strlen(x)
Not a very great answer.
If the string is google, this tries to access the 2147483649th character in the string "\0", which causes a segmentation fault, otherwise the length of the string is returned.
Uiua 0.11.0, 14 bytes
⧻⍤,¬≍"google".
Explanation
⧻⍤,¬≍"google".
. # Copy the string
≍"google" # Check if it matches the string "google"
⍤,¬ # If it does NOT match, proceed further. If it does, throw an error
# with the string "google" (the 2nd value on stack)
⧻ # Get the length of the string
Acc!!, 123 bytes
-1
Count i while _/256^i {
_+N*256^(i+1)+1
}
_%256+0/(_/256-2926266033336167)
Write _/100+48
Write _/10%10+48
Write _%10+48
Try it online! (Note: The official interpreter occasionally, but not always, adds a trailing newline to the end of user input, and it is impossible to tell from within the language if the newline was manually entered or automatic. Thus, an input of "bing" becomes "bing\n" and evaluates to length 5.)
Example output (with input "google")
Acc!!
Traceback (most recent call last):
File "/opt/accbb/acc.py", line 108, in <module>
main()
File "/opt/accbb/acc.py", line 15, in main
exec(code, {"inputStream": inputStream()})
File "<string>", line 8, in <module>
ZeroDivisionError: integer division or modulo by zero
Explanation
# Accumulator has length at _%256, followed by input bytes starting at _/256.
# Read all input
-1 # Trigger loop to start and also correct off-by-one
Count i while _/256^i { # While last byte read nonzero:
_ + N*256^(i+1) + 1 # Read another byte and increment length
}
# Isolate length byte, and divide by zero if the input was google
_%256 + 0/(_/256-2926266033336167)
# Print length byte
Write _/100+48
Write _/10%10+48
Write _%10+48
Vyxal, 8 bytes
ɽ‛»¾=ßṀL
Assumptions
- Program itself is the function g
- Program takes exactly one input
"Google" being in the code page dictionary allows for a 3 byte representation: ‛»¾
If input is equal to "google", case insensitive, will attempt to call a triad with too few arguments, else compute length.
TypeScript's Type System, 113 (or 73) bytes
type F<I,S=I,L extends{}[]=[]>=S extends`${infer A}${infer B}`?F<I,B,[...L,A]>:I extends"google"?F<I>:L["length"]
Try it at the TypeScript playground!
Recursively take each character of the string and put it into a list. When no characters remain, check if the initial string was "google"; if so, recurse with the same initial string (i.e. recursion error), otherwise return the length of the list. (We must split the string into a list of characters because that's the only way to get the string's length in TypeScript's Type System.)
Or, by taking input as a tuple of characters instead of a string - 73 bytes:
type F<S extends{}[]>=S extends["g","o","o","g","l","e"]?F<S>:S["length"]
Try it at the TypeScript playground!
We can skip the whole recursive splitting process by taking the input directly as a list of strings, and comparing to the split string "google", with the same recursion error idea as the above.
APL (14)
(⍴÷'google'∘≢)
Explanation:
⍴: length÷: divided by'google'∘≢: argument is not equal to'google'.
⍴ gives the length of the string, which is divided by 1 if the string does not equal google (which gives the length back unchanged), or by 0 if the string does equal google (giving an error).
GNU sed, 102 bytes
I did stumble over this 137 byte sed solution, but besides the counting method can be improved the probably shortest way to produce an error with GNU sed is using the e flag to execute illegal code:
s/^google$/./e
s/.$/#/
:1
/#9*$/s/#/&0/
s/.9*$/_&/
h
y/0123456789/1234567890/
x
G
s/_.*_//
s/.//
/#/b1
Of course, you could save two more bytes using the buggy old version with empty labels.
05AB1E, 8 bytes
g¹“й“Ê÷
Uses the CP-1252 encoding. Try it online!
Explanation:
# Implicit input
g # Take length
¹ # Get first input
“й“Ê # != compressed form of "google"
÷ # Integer division (Zero Division Error if invalid)
05AB1E, 10 bytes
Code:
g“й“¹Q</Ä
Explanation:
g # Take the length of the implicit input
“й“ # Compressed version of "google"
¹Q # Take the first input again and check if equal to "google"
< # Decrement on the bool
/ # Divide the length by the value
Ä # Take the abstract value of the result
# This is then implicitly printed
Try it online!. When the input is google, nothing is printed due to a division by zero exception.
Python 3, 30 bytes
lambda x:len(x)//(x!="google")
Try it online! Python 3 port of xnor's Python 2 answer. The floor division operator is necessary to convert back to an integer instead of leaving it as a float.
Red, 34 bytes
func[g][length? any[g ="google"g]]
Try it online! (the code so dense that it crashes the program).
Red, 46 bytes
func[a][(length? a)/ either a ="google"[0][1]]
My first attempt on writing something somewhat serious with Red
sighs in boolean cannot be used as int
Knight, 17 bytes
O/L=gP!?g"google"
Requires a patch to fix an errata in the """golfed""" C interpreter, where it will leave a newline in the input from PROMPT. This matches the behavior of the AST interpreter and the wording of the spec.
This is the simple division by zero method.
# print length(g = prompt()) / (g != "google")
OUTPUT / (LENGTH(= g PROMPT)) (! (? g "google"))
Relies on division by zero throwing an exception. The AST interpreter will always throw an exception in software, but for the golfed interpreter, it requires the x86 behavior of throwing an exception on the hardware level.
Zsh, 18 bytes
<<<$#1>$1
<^google
Explanation:
<<<$#1:$1: the input#: length<<<: and print it
>$1: redirect that output to a file called the input^google: try and find a file with any name other thangoogle<: and print its contents
So if the file created was called google, then no file will be found and an error message will appear. But if the file was called anything else, then its contents is the length of the input, and it will be outputted.
VBScript, 47 bytes
sub f(x)
msgbox len(x)/abs(x<>"google")
end sub
VBScript will return -1 for True, so we have to abs() it. And attempts to divide it by the length, like the python answer.
05AB1E, 8 bytes
'йQiFëg
'йQiFëg # full program
i # if...
# implicit input...
Q # is equal to...
'й # "google"...
F # then...
# (implicit) do nothing...
# implicit input...
F # times
ë # else...
g # push length of...
# implicit input
# implicit output
Vyxal, 7 bytes
‛»Ǒ≠/÷L
‛»Ǒ≠/÷L
‛»Ǒ # "google"
≠ # ↑ != input
/ # split input into ↑ even pieces. If input is "google", this will be 0, consequently causing an error
÷L # Get the length of the item
Python 3.8 (pre-release), 37 35 bytes
lambda s:len(s)if"google"!=s else~s
Reverted to this solution whilst comparing to the other answers and noticing that it was the same. -2 bytes thanks to the suggestion by Makonede to use ~s instead of s.s
Raises TypeError: bad operand type for unary ~: 'str'
Racket, 46 bytes
(λ(x)(if(eq? x"google")(-)(string-length x)))
Gives an arity mismatch error on the input "google" since - needs at least one argument.
Clojure, 47 44 bytes
Old answer
#(/(count %)(get{false 1 true 0}(= %"google")))
New Answer
#(/(count %)({false 1 true 0}(= %"google")))
Removed the get function call, because you can call a hashmap with a key to get the value.
Lua, 35 bytes
load'return #(...=="google"or ...)'
Idea is like one in @QuertyKeyboard's answer, but better optimized: load is used to create function and inverting check for "googleness" allows us to save one byte by replacing and with or.
Again, if full programs are allowed, we can cut down to 29 bytes!
Lua, 29 bytes
print(#(...=="google"or ...))
JavaScript (V8), 41 bytes
s=>s[['length']['google'==s|0]].toFixed()
JavaScript (V8), 33 bytes
s=>[_=>s.length]['google'==s|0]()
JavaScript (V8), 28 bytes
s=>[s]['google'==s|0].length
W d, 10 9 bytes
This is a full program but is technically also a function.
*↔XÑ║╜▄]ÿ
Explanation
Decompressed:
-Fl'I`nakS/
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
Python 2, 29
lambda x:len(x)/(x!='google')
Gives a ZeroDivisionError on "google", and the length otherwise. This takes advantage of Python's booleans equaling 0 and 1.
Keg, 16 bytes
:`google`=[0/|÷!
Attempt ruined by the fact that google isn't in Keg's dictionary. That's why I use DuckDuckGo, which at least has parts of it's name in the dictionary!
Brachylog, 12 bytes
"google"∧∈|l
Since Brachylog simply fails a predicate that tries to divide by 0, the error here comes from trying to unify the output with a list containing an entirely un-instantiated variable instead. If the input can be unified with google, it errors, and otherwise this predicate outputs the length of the input (add one more byte w to the end to make it a full program that prints the length).
GameMaker Language, 46 bytes
x=argument0
return string_length(x)/x!=google
Uses the same logic as this Python answer, abusing GMLs type coercion making the function divide by zero if the string equals google
I also haven't and can't test this because I currently don't have GameMaker installed, just made this from memory
Stax, 9 bytes
ôK▓ÿσ▄Ω?╠
Well, defeated some of the 10-byters ...
Explanation
Uses the unpacked version to explain.
`!:X9`|^hy%
`!:X9` "google"
|^ array xor (can't use `-` here, which means **set** difference)
h head of array, error if it is empty
y% length of input
SmileBASIC, 41 38 bytes
DEF G(S)RETURN LEN(S)/(S!="google")END
If S is not google, the length is divided by 1. Otherwise it's divided by 0, causing an error.
G("SAND")
4
G("google")
Divide by 0 in 0:1
C, 35 bytes
-Df(s)=strlen(s)/strcmp(s,"google")
Compiler flag :) Returns the length of the string provided. If it's google it throws a Floating point exception.
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.
Bash
[ $1 == google ]; return $((${#1}/$?))
Aceto, 19 bytes
rdM"google"J=$L€lp
Took me a while, but I finally got it. Aceto uses a hilbert curve for it's ip, which is really annoying.
r grabs input d duplicates it M pops the top value and stores it in quick memory "google" pushes google on the stack, but with a lot of spaces in between. - splits it on whitespace J concatenates it = pushes a bool on the stack: whether the top two values are equal $ asserts that the top value is truthy, if not it raises an error. Don't ask me why i don't have to negate it L loads the quick memory € explodes the string, putting each char as a separate val on the stack l takes the height of the stack p prints that num
Excel VBA, 52 Bytes
Subroutine that take input a as unassigned/variant of expected type variant/String and outputs to the VBE Immediates window. If a = "google" throws Run-time error '3': Return without GoSub else outputs the length of the input a.
Sub g(a)
If a="google"Then Return
Debug.?Len(a)
End Sub
Ruby, 29 bytes
I first came up with something very similar to @Borsunho's first attempt, but mine was slightly longer and he posted his before I was done. Came up with this before his 30 bytes edit :)
->s{s[/^(?!google$).*/].size}
Usage examples:
$ irb
2.2.1 :001 > f = ->s{s[/^(?!google$).*/].size}
=> #<Proc:0x007fa0ea03eb60@(irb):1 (lambda)>
2.2.1 :002 > f[""]
=> 0
2.2.1 :003 > f["bing"]
=> 4
2.2.1 :004 > f["google"]
NoMethodError: undefined method `size' for nil:NilClass
from (irb):1:in `block in irb_binding'
from (irb):4:in `[]'
from (irb):4
from /Users/daniel/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'
edit: Two years and some Ruby versions later
Ruby, 25 bytes
->s{+s[/^(?!google$).*/]}
Replaced String#size with the new unary plus. Try it online!
MATLAB, 63 41 40 38 36 bytes
Thanks to Tom Carpenter for shaving off 1 byte!
Thanks to Stewie Griffin for shaving off 2 bytes!
@(x)nnz(x(+~strcmp('google',x):end))
Unlike the other more elegant solutions, performing a division by zero operation in MATLAB will not give an error, but rather Inf. This solution finds the length of the string by nnz. The string that is produced is in such a way that you index from the beginning of the string to the end, which is essentially a copy of the string. However, what is important is that the beginning of where to access the string is produced by checking whether or not the input is equal to 'google'. If it isn't, this produces a beginning index of 1 and we index into the string normally... as MATLAB starts indexing at 1. Should it be equal, the index produced is 0 and MATLAB will throw an indexing error stating that the index needs to be a positive integer. The extra + is to ensure that the output of the equality check is numerical rather than Boolean/logical. Omitting the + will produce a warning, but because this challenge's specifications doesn't allow for warnings, the + is required... thus completing the code.
Example uses
>> f=@(x)nnz(x(+~strcmp('google',x):end)) %// Declare anonymous function
f =
@(x)nnz(x(+~strcmp('google',x):end))
>> f('bing')
ans =
4
>> f('google')
Subscript indices must either be real positive integers or logicals.
Error in @(x)nnz(x(+~strcmp('google',x):end))
A more fun version, 83 77 76 74 72 bytes
Thanks to Tom Carpenter for shaving off 1 byte!
Thanks to Stewie Griffin for shaving off 2 bytes!
@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end');
The above isn't an official submission, but it's something that's a bit more fun to run. Abusing eval within anonymous functions, what the code does is that it checks to see if the input string is equal to 'google'... and if it is, this will open up MATLAB's built-in web browser and shows Google's 404 error page trying to access the subpage located at i when that doesn't exist. If not, we display the length of the string normally.
Example uses
>> f=@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end'); %// Declare anonymous function
>> f('bing')
ans =
4
>> f('google')
>>
The last call using 'google' gives us this screen:
05AB1E, 10 bytes
“й“Qi.0ëg
“й“ # Push "google".
Qi # If input == "google"...
.0 # Divide by 0.
ë # Else...
g # Return length of input.
Jelly, 10 bytes
ßL⁼“æ8Ụ»$?
Try it online! (with "google" as input)
Try it online! (with "bing" as input)
How it works
ßL⁼“æ8Ụ»$? - Main link. Argument: s (string)
? - if...
⁼ $ - the input is equal to...
“æ8Ụ» - "google"
- then
ß - call the main link (segfault)
- else
L - return the length of the input
Mathematica, 33 bytes
#=="google"&&1/0||StringLength@#&
TFW Length doesn't work on strings. >.>
shortC, 21 bytes
Df(s)Ss)/Ms,"google")
Df(s)defines a functionfthat takes one arguments.Ss)calculates the length ofs.Ms,"google)comparessto "google".Ss)/Ms,"google")divides the length ofsby0if the strings are equal. This throwsfloating point exceptionif they're equal.
GNU sed, 137 bytes
Adding to the diversity of languages used here, I present a sed answer. There are no integer types or arithmetic operations in sed, so I wrote an increment method to get a string's length (111 bytes).
/^google$/{:;s:a*:&&a:;t}
s:^:0,:
:i
s:^9*,:0&:
s:.9*,:/&:;h
s:[0-9]*/::
y:0123456789:1234567890:
x;s:/.*::
G;s:\n::
s:,.:,:
/,./ti
s:,::
The first line of code checks if the input string is google, and if so it continuously increases the pattern space until a memory allocation error is raised. Try it online!
Tests: from a virtual Linux OS I setup with low memory
test@test:~$ sed -f google_error.sed <<< "yahoo"
5
test@test:~$ echo $?
0
test@test:~$ sed -f google_error.sed <<< "google"
sed: couldn't re-allocate memory
test@test:~$ echo $?
4
Ruby, 19+1 = 20 bytes
Uses the -n flag. Because -n includes the trailing newline for any line of input, it must be piped in from a file w/o the trailing newline or it will not give the error and will instead return 7.
p +~/(?<!^google)$/
Version that requires a trailing newline in the input, so you can type in directly from STDIN, for 20+1=21 bytes
p +~/(?<!^google)\n/
Alternate version that works with or without trailing newlines, for 23+1=24 bytes.
+(! ~/^google$/&&p~/$/)
All versions return the following error:
undefined method `+@' for nil:NilClass (NoMethodError)
Edited processing JS: 68 bytes
var a =function(i){if(i==="google"){throw"a";}else{print(i.length);}};
Used a edited version of processing. When run here you can see it works. If you input google then the error buddy pops up without any message. This is my first golf!
Edited version of processing (didn't cheat by making my own version) https://github.com/Khan/processing-js
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.
Japt, 14 bytes
U¥`goog¤`?Þ:Ul
Explanation
U¥`goog¤`?Þ:Ul
U // U is the input
¥ // ¥ is the Unicode shortcut for ==
goog¤ // "google" compressed
` ` // backticks are used to uncompress goog¤
Þ // An undefined variable
Ul // l is a built-in that returns the length of U
// Implicit: output result of last expression
JavaScript, 25 bytes
p=>p=='google'?_:p.length
Java, 84 68 37 bytes
b->b.equals("google")?1/0:b.length();
This is a java.util.function.Function<String, Integer> that divides by 0 if b is the string google.
Clojure, 35 33 bytes
#(/(count %)(if(= %"google")0 1))
(def g #(/(count %)(if(= %"google")0 1)))
(g "google")
ArithmeticException Divide by zero clojure.lang.Numbers.divide
(g "bing")
4
Unfortunately, 0 is true is Clojure, and there aren't any simple ways of casting a bool to an int anyways, so I had to spend some bytes on a ternary. Still ended up being shorter than my first attempt.
V1: #(if(= % "google")(/ 1 0)(count %)))
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);');}
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
Perl 6, 19 bytes
{.comb/!/^google$/}
.comb returns list of characters in string (which in numeric context is a number of characters, I use this instead of .chars because it's shorter). Because there is nothing before a period, Perl 6 assumes you wanted to call a method on $_. This is divided by a negated match on regex ^google$ with implicit $_ variable. If it matches, the value becomes 0, and Perl 6 errors because of a division by zero.
Example:
> {.comb/!/^google$/}("qwerty")
6
> {.comb/!/^google$/}("google")
Attempt to divide 6 by zero using div
in any interactive at src/Perl6/Compiler.nqp line 62
Ruby, 26 bytes
Not shorter than the existing ones, but an alternative solution.
->x{(x=='google'||x).size}
If given google, it tries to do true.size which results in an error:
NoMethodError: undefined method `size' for true:TrueClass
Python 2, 46 bytes
a=raw_input()
print len(a)if a!='google'else b
Errors out on input of "google" because b is an undefined identifier, but succeeds on other strings since control never reaches b in those cases.
Perl, 31 29 bytes
sub{$_=pop;y///c/!/^google$/}
-2b thanks to manatwork
Usage:
sub{$_=pop;y///c/!/^google$/}->("google")
If I could get away with a program rather than a function, the following would be valid with only 20 bytes (+1 byte command line)
$_=y///c/!/^google$/
Error is division by zero.
Explanation:
y///c returns the length, then !/^google$/ will return 0 iff input matches 'google'.
Usage:
perl -p entry.pl input.txt
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. :)
C++, 77 Bytes
#include <string>
int G(std::string S){1/int(S!="google");return S.length();}
Python, 47 bytes
a=input()
print(0/0 if a=="google" else len(a))
Scratch, 16 bytes

(scoring used)
Stopping the project is the closest thing to an error that I can get.
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^.
Octave, 63 bytes
I know it is longer than the Matlab solution (which would work in Octave too), but it is particularly evil. I am making an anonymous function (evil) using cell array (evil) literals (evil) containing function handles dependent on a callback function (itself, thus recursive, evil) that must be passed via argument. Then I create another anonymous that basically reduces the function to the string argument and fixes the second argument of f as f (very evil). Any sane human would never do this, because it is almost as unreadable as Perl or regex (or cjam/pyth/any other esolang).
So if the string is not 'google' the second argument of the cell array will be called which outputs the length of the string. Otherwise the first function will be called, which is passed as a callback (and passes itself as callback to itself too) which later is the function itself. The error is basically some maximum recursion depth error.
f=@(s,f){@()f(s,f),numel(s)}{2-strcmp(s,'google')}();@(s)f(s,f)
Pyth, 12 bytes
/lznz"google
len(input())/input()!="google"
Hoon, 32 bytes
|*
a/*
?<
=(a "google")
(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/*
?<
=(a "google")
(lent a)
3
> %. "google"
|*
a/*
?<
=(a "google")
(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]
Molecule (v5.6+), 16 bytes
I_"google"=?p¿#
Explanation:
I_"google"=?p¿#
I_ duplicate
"google"= add google and compare
?p¿ if true, do a primality test on "google"
# get length
This way the program will error and shutdown if it does a primality test on a string.
TI-83 Basic, 21 bytes
Simple solution. (Lowercase tokens are two bytes each).
length(Ans)/(Ans≠"google
Alternate solution (22 bytes):
If Ans="google
.
length(Ans
Alternate solution (23 bytes):
length(Ans)+0/(Ans≠"google
Python 3, 30 bytes
lambda u:[len][u=='google'](u)
Indexes the 1-element function list, raising an IndexError if the u=='google' predicate is True (= 1). Such functional.
Much variants. Wow:
lambda u:[len(u)][u=='google']
lambda u:len([u][u=='google'])
If the challenge was inverted (error on everything not "google"), could save a char:
lambda u:{'google':len}[u](u)But you already know the length, so just hardcode it.
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)
getNum(x/"google")&""0+dim(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.
Rust, 41 chars
rust solution, provided by a friend who does have a rep of 10 to post (and asked me to post it on his behalf).
|x:str|{if x=="google"{panic!();}x.len()}
C++14, 42 chars
For giggles, as I did not see a very good c++ solution. My TI-89 solution is superior at 34 bytes
[](auto s){return s.size()/(s!="google");}
Fuzzy Octo Guacamole, 19 bytes (non-competing)
"google".^={e}_!r_;
"google' pushes the string "google" to the stack.
. swaps the active stack.
^ gets input.
= is the rocketship operator, pushes 0 for equality, -1 for less than, and 1 for greater than as x <=> y with x as the top of the active stack, and y as the top of the inactive one.
{ and } denote an if statement, like bf's goto/if thing. Skips the code inside braces if the top of the stack is truthy.
e errors. That's it.
_ pops the stack, this time is just to remove the equality check result and show the input.
! sets the universal register to the top of the stack, or the length of the top of the stack for strings/lists.
r clears the register and pushes it back to the stack.
_ pops again, and
; prints.
So this checks for equality, then does a clumsy cast to int, and than prints the result.
Julia, 26 24 chars
Two characters shorter now, thanks to Dennis.
The challenge says ‘[...]in as few amount of Unicode characters as possible’, so I’m going for ≠ and ℕ in my solution.
Anonymous function. Just assign it to a variable:
f->f≠"google"?endof(f):ℕ
In the case of "google" you get the error message:
julia> (f->f≠"google"?endof(f):ℕ)("google")
ERROR: UndefVarError: ℕ not defined
As ordinary function (26 chars):
x(f)=f≠"google"?endof(f):ℕ
ℕ is an unassigned variable, so it produces an error message.
If that doesn’t count or is against the rules, then just using !f (one char longer) instead would produce an error anyway. Boolean not is not defined for strings.
Factor, 55 53 49 bytes
: g ( s -- l ) dup length swap "google" = not / ;
Throws the string "google". Or I could just divide the length of the string by if it's not throw happens to be the same length as 0 0 /. Or I could just divide a string by a number...google...
Example use:
cat @ mint-kitty : ~/projects/factor/factor(master??!) $ ./factor -run=listener
Factor 0.98 x86.64 (1742, heads/master-0bb3228063, Tue Mar 15 14:18:40 2016)
[Clang (GCC 4.2.1 Compatible Ubuntu Clang 3.6.2 (tags/RELEASE_362/final))] on linux
IN: scratchpad : dont-google ( str -- int ) dup "google" = [ throw ] [ length ] if ;
IN: scratchpad "bing" dont-google
--- Data stack:
4
IN: scratchpad "google" dont-google
google
Type :help for debugging help.
--- Data stack:
4
IN: scratchpad
The error in the UI:
Gogh, 20 bytes
÷GD$"google"={¤+}¦:$
Usage:
./gogh o '÷GD$"google"={¤+}¦:$' "google"
Explanation
“ Implicit input ”
÷ “ Duplicate the input ”
GD “ Push a range of [1, len(input)] ”
$ “ Rotate input to the TOS ”
"google"= “ Determine equality ”
{¤+}¦: “ Error if equals "google" (empties stack and tries addition) ”
$ “ Leave the length on the stack ”
“ Implicit output ”
Mathcad, 23 "bytes"
And it even works with foreign languages ...
Note: Mathcad displays errors by showing the expression in red; clicking on the expression shows the error message.
jq, 39 characters
def g(s):s|length/({"google":0}[s]//1);
Sample run:
bash-4.3$ bin/jq -n 'def g(s):s|length/({"google":0}[s]//1); g("google")'
jq: error (at <unknown>): number (6) and number (0) cannot be divided because the divisor is zero
bash-4.3$ bin/jq -n 'def g(s):s|length/({"google":0}[s]//1); g("yahoo")'
5
On-line test:
Lua, 42 bytes
function g(s)return #(s~='google'and s)end
This creates a function g that takes an argument s and (assuming it is a string) returns the length (#) of the result of the evaluation s~='google'and s, which equates to s if s is not 'google', or false if it is. Since there is no length of false, if s is google, this will error, else, it will return the length. Simple and effective.
I know there are other Lua answers, and that I could shorten this by using io.read(), but I'm going to disregard both of those for the same reason: they don't actually use functions, like the question specifically calls for.
If I'm wrong in that it doesn't need to be a function, we can cut this to 32 bytes by doing:
s=io.read()g=#(s~='google'and s)
Milky Way 1.0.0, 18 bytes
This language was created after the challenge was posted.
'?{"google"b~z~y!}
Explanation
' # read input from command line
?{ ~ ~ } # if-else statement
"google" # push "google" to the stack
b # == on top two stack items (input and "google")
z # non-existent opcode raises an exception
y # push the length of the TOS to the stack
! # output the TOS
Milky Way (current version), 18 bytes
'?{"google"b_z_y!}
Usage
The code is called via the command line as follows:
./mw <path-to-code> -i <input>
Go, 110 102 93 92 bytes
It makes sense to use a language developed by Google employees to Google Google!
note that this is actually a valid, compilable program, unlike the other go answer.
will take input forever until "google" is input:
package main
import."fmt"
func main(){a:=""
Scan(&a)
if a=="google"{panic(0)}
Print(len(a))}
example i/o:
bing
4
oogle
5
google
panic: 0
goroutine 1 [running]:
runtime.panic(0x480e60, 0xc21000a190)
/usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
main.main()
/home/cat/projects/go/src/not-google/main.go:10 +0x115
exit status 2
ungolfed:
package main
import . "fmt"
func main() {
a := ""
Scan(&a)
if a == "google" {
panic(0)
}
Print(len(a))
}
apparently i had forgotten that var a string is just "" aka empty string. sigh.
Java, 96 Bytes
This should work, but IDK for sure since I cant assess a computer at the moment:
Golfed:
int g(String s){if(s.equals("google"))throw new
IllegalArgumentException();return s.length();}
Ungolfed:
int g(String s){
if(s.equals("google")) throw new IllegalArgumentException();
return s.length(); }
I realize I could proably shorten this, let me know in the comments.
Ruby, 46 32 29 bytes
->s{b=Hash.new(0);b['google']=nil;b[s]+s.size}
New shortened approach:
->g{(g.to_a-['google'])[0].size}
Reduced 3 bytes with manatwork's suggestion
->g{([g]-['google'])[0].size}
PARI/GP, 21 19 bytes
x->#x/(x!="google")
Example:
? g = x->#x/(x!="google")
%1 = (x)->#x/(x!="google")
? g("bing")
%2 = 4
? g("google")
*** at top-level: g("google")
*** ^-----------
*** in function g: #x/(x!="google")
*** ^--------------
*** _/_: impossible inverse in dvmdii: 0.
*** Break loop: type 'break' to go back to GP prompt
break>
MS T-SQL, 63 bytes
CREATE PROC g @p CHAR(9) AS SELECT IIF(@p='google',1/0,LEN(@p))
Ungolfed code;
CREATE PROC g
@p CHAR(9)
AS
SELECT IIF(@p='google',1/0,LEN(@p))
Called by either EXEC g 'string' or simply g 'string'
Command: EXEC g 'gogle'
Result: 5
Command: EXEC g 'google'
Result: Msg 8134, Level 16, State 1, Procedure g, Line 1 Divide by zero error encountered.
Game Maker Language, 60 bytes
a=argument0;if a="google"a=1/0show_message(string_length(a))
ಠ_ಠ, 110 bytes (noncompetitive)
ಠ_ಠ
ಠgoogleಠ
ಠ=ಠ
ಠ"ಠ
ಠ$ಠ
ಠ$ಠ
ಠ11ಠ
ಠ13ಠ
ಠ(ಠ
ಠ?ಠ
ಠ_ಠ
ಠ#ಠ
ಠ^ಠ
Zsh and bc, 29 bytes
[ "$1" = google ];bc<<<$#1/$?
Sample output:
$ zsh not_google.sh oogle
5
$ zsh not_google.sh google
Runtime error (func=(main), adr=5): Divide by zero
Explanation:
The first command exits true (zero) when the argument equals "google" and false (one) otherwise. That exit code is stored in $? until another command completes, allowing us to divide by that number.
We then run bc (with input via herestring) to compute the length of the argument divided by that exit code. This is either length ÷ 1 (the length) or length ÷ 0 (an error).
An un-golfed version:
if [ "$1" = google ]; then
divisor=0
else
divisor=1
fi
length="${#1}"
echo "$length / $divisor" |bc
Bash and bc, 31 bytes
This uses the same logic, but bash can't handle $#1 without braces:
[ "$1" = google ];bc<<<${#1}/$?
Zsh and bc, 26 bytes (also errors on empty string)
This version also has an error when given an empty string, so I assume it doesn't count. It has the exact same output as the previous version (except when given an empty string or no argument).
bc<<<$#1/(0!=${#1#google})
Un-golfed version of 26 byte answer:
length="${#1}" # the length of the first argument
unprefix_google="${1#google}" # google → "", googler → r, goog → goog, "" → ""
length_unprefix_google="${#unprefix_google}"
if [ 0 != "$length_unprefix_google" ]; then
divisor=1 # $unprefix_google is an empty string
else
divisor=0 # $unprefix_google is not empty
fi
echo "$length / $divisor" |bc
O, 17 bytes
{e\"google"=L@N?}
To use this function:
"wow" {e\"google"=L@N?} ~
Explanation:
e\ Get the length of the string and swap it on the stack
"google"= Compare the string
? If
L@ True (it is google): Rotate top three elements on the stack, throwing an underflow error
N False (it is not google): do nothing
Length is printed out automatically
TI-BASIC, 15 bytes
Heck, while we're at it, might as well get a TI-BASIC answer in here.
Input format is "string":prgmNAME. Credit to Thomas Kwa for finding it first!
length(Ans)+log(Ans≠"GOOGLE
(Guide: add 1 byte for each lowercase letter replacing an upper-case one. So s/GOOGLE/google/g => +6 bytes.)
ahhhhh test cases!
"GOGGLE":prgmG
6
"BING":prgmG
4
"GOOGLE":prgmG
Error
Windows Batch, 118 characters
IF /I "%string%"=="google" exit
echo %string%> string.txt
for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )
Output is %stringlength%.
Full code:
@echo off
del string.txt
cls
echo Type your string
echo.
set /p string=String:
IF /I "%string%"=="google" goto err
echo %string%> string.txt
for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )
cls
echo %stringlength%
pause
del string.txt
:err
color c
echo There seems to be an error with your input...
pause>nul
Modified from Joshua Honig's answer, here.
Perl, 49 46 39 31 bytes
sub g{sub g{$_=pop;y///c/!/^google$/}}
Call with g(string), print with print g(string).
How it works
The ternary operator only evaluates the expression if the condition is met. So when the input isn't google, it simply returns the original string and passes it on to length. However, is the input is google, it tries to divide by zero and causes this error:
Illegal division by zero at filename.pl line 1.
And as we all know, dividing by zero will break the internet (and the rest of reality).
Changes
- Saved 3 bytes by changing
returntoprintand removing unneeded parentheses. - Saved 6 bytes thanks to @manatwork, and saved an additional 1 byte by re-arranging my code.
- Saved 8 bytes and fixed an error thanks to @Grimy.
Powershell 34 Bytes
param($a)$a.length*($a-ne'google')
Multiply length by 0,1 boolean value of not-equal google.
Gives 0 if google (not case-sensitive), length otherwise.
OCaml 42 bytes
This does exactly what is asked1: it returns a function which returns the length of its (string) argument, except when the argument is "google", in which case it fails with:
Exception: Division_by_zero.
function"google"->0/0|s->String.length s;;
It doesn’t provide any way to actually call that function, though. In order to do that, you could either write:
(function"google"->0/0|s->String.length s)"some string";;
or you could, you know, give it a name.
let f=function"google"->0/0|s->String.length s;;
f"bing";;
Unpacked, this would give:
(* let f be function with one argument. *)
let f = function
(* If the argument matches exactly "google", return 0/0 *)
| "google" -> 0 / 0
(* If no previous cases were a match, give your argument the name 'string'. *)
(* and return its length. *)
| string -> String.length string
;;
(* Call f with "bing" as it’s argument. *)
f "bing";;
The type of 0 / 0 is int, so the function is correctly typed as string -> int.
- Well, I must admit I have not checked these pesky Unicode details.
Clojure (43 bytes)
I know Clojure has been answered before, and shorter too, but I love the way this one generates a StackOverflow error when "google" is passed in:
(defn f[s](if(= s "google")(f s)(count s)))
Example:
user=> (f "google")
StackOverflowError user/f (NO_SOURCE_FILE:213)
JavaScript, 25 Bytes
Nice and simple JavaScript example:
e=>e!='google'?e.length:g
If "google" is entered then it passes a ReferenceError
Example
alert((e=>e!='google'?e.length:g)('test'))
Rust, 170 bytes
I didn't see anything in rust, so I figured I'd make one. Hopefully someone can improve this a bit! (or perhaps a byte... see what I did there ;) )
use std::io;fn main(){let s=io::stdin();let mut b=String::new();s.read_line(&mut b).unwrap();let l=b.len();b.truncate(l-2);assert!(b!="google");println!("{}", b.len());}
Throws the error:
thread '<main>' panicked at 'assertion failed: buffer != "google"', main.rs:7
when you try "google."
Ungolfed Code:
use std::io;
fn main() {
let stdin = io::stdin();
let mut buffer = String::new();
stdin.read_line(&mut buffer).unwrap();
let leng = buffer.len();
buffer.truncate(leng-2);
assert!(buffer!="google");
println!("{}", buffer.len());
}
PHP 5.4, 81 bytes
<?function g($s){eval('if(isset('.($s==google?"$s":'$s').'))print strlen($s);');}
// following added for easy testing, not included in bytes count
g($argv[1]);
Everyone's favourite error when searching for Google! Didn't work out quite as obfuscated as I'd hoped...
Usage:
php 58891.php 'test'
4
php 58891.php 'google'
# error
J, 18
#`^@.('google'-:])
Usage:
#`^@.('google'-:]) 'googl'
5
#`^@.('google'-:]) 'google'
|domain error
| #`^@.('google'-:])'google'
Explanation
Count (#) if y does not match (-:]) the string 'google', but if it does match, compute e to the power of the string 'google', which is an error.
Ruby, 41 characters
def g(s)puts s!="google"?s.length: a end
><>, 47 bytes
i:0(?\
?\ln;>~l6=
"\ "elgoog
!\{=?!\l ?
=< ;n6<
Here's a line-by-line breakdown:
i:0(?\
A standard ><> input loop, pushes the input string followed by -1.
?\ln;>~l6=
Starts at >. Discards the -1, checks the length is equal to 6. If it is, move to next line, otherwise gets the length, prints, and exits.
"\ "elgoog
Starts at \. Pushes 'google' in reverse. If the input string was google, stack is now googleelgoog
!\{=?!\l ?
Starts at the first \. Rolls the stack one to the left. If top two elements aren't equal, moves to next line. Otherwise, if the stack is length is zero, the strings are equal, so also step to next line.
=< ;n6<
Starts on the 1st < if the string was 'google'. This is only reached when the stack is empty, so attempting to pop any number of values will cause an error - in this case, = is used. If the string wasn't 'google', outputs 6 and exits.
Go: 92, 63, 59 bytes with panic instead of error
func g(s string)int{if s=="google"{panic(0)};return len(s)}
Groovy, 32 chars
e={(it=='google'?0:it).length()}
A similar approach like a bunch of others here. The closure tries to return the length of either
- the passed string, if it's not equal to
google - the length of the integer
0, if the passed string is equal togoogle, which results in a MissingMethodException as there's noInteger.length()method
Tested with
e('bing')
e('google')
e('duckduckgo')
Befunge-93, 59 characters
<+1\_v#+1:~
vp00$<
<*_v#:\
v_v>$"google"*****-!#
< >00g.@>1
Befunge has no way to actually throw an error, so I just push an "infinite" number of 1s onto the stack. An error will happen somewhere eventually...
Explanation
Anyway, this works by reading in the input and simultaneously keeping track of its length.
<+1\_v#+1:~
This length is stored at location 0,0.
vp00$<
The remaining numbers are multiplied together.
<*_v#:\
This is then compared to the product of "google".
v_v>$"google"*****-!#
If they are the same (i.e., if their difference is zero), then the "error" is thrown. Otherwise, the value stored at 0,0 is retrieved and outputted.
< >00g.@>1
AHK, 75 bytes
Inputbox,s
MsgBox % a(s)
a(b)
{
if (b!="google")
return StrLen(b)
throw b
}
there is no proper stdin and stdout support in ahk so im using inputbox and msgbox, the concept is the same tho.
JavaScript ES6, 34 27 25 characters
f=>f=='google'?Δ:f.length
Throws a ReferenceError on Δ for google.
alert((f=>f=='google'?Δ:f.length)('test'))
Pyth, 14 13 characters
L/lbnb"google
Defines a named function y.
This divides the length by 1 if the string is not google and by 0 otherwise. The idea is not novel, but I came up with it independently.
How it works
L Define y(b):
lb Compute len(b).
nb"google Compute (b != "google").
/ Set _ = len(b) / (b != "google").
Return _. (implicit)
C#, 43 bytes
An improvement over Salah Alami's answer. Recurses to throw a stack overflow exception on providing "google"
int g(string s)=>s!="google"?s.Length:g(s);
><>, 108 bytes
i:"g"=1-?v\]
i:"o"=1-?v\
i:"o"=1-?v\
i:"g"=1-?v\
i:"l"=1-?v\
i:"e"=1-?v\
i:01-=1-?v\
>i:0)?v~l n;
^ < <
Matlab, 50 51 bytes
Thanks to @rayryeng for removing 1 byte.
This uses an anonymous function, and exploits the fact that the error function with an empty input issues no error.
It's noteworthy that the error given for input 'google' is meta: it's an error using the error function.
@(s)eval('error(find(strcmp(s,''google''))),numel(s)')
Examples:
>> @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
ans =
@(s)eval('error(find(strcmp(s,''google''))),numel(s)')
>> ans('abcd')
ans =
4
>> @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
ans =
@(s)eval('error(find(strcmp(s,''google''))),numel(s)')
>> ans('google')
Error using error
The message must be specified as either a string or a message structure.
Error in @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
C++14, 47 bytes
[](auto s){return s=="google"?throw:s.size();};
This is a generic lambda expression in C++14. It simply checks if the argument (string) is "google" and calls terminate if it is - else it returns the length of the string.
It can be called as such:
[](auto s){return s=="google"?throw:s.size();}("some_string"s);
Zereges has a very similar answer here written in C++11. Since this was C++14 it was O.K. by him for me to post this.
CJam, 16 characters
{_,\"google"=!/}
This divides the length by 1 if the string is not google and by 0 otherwise. The idea is not novel, but I came up with it independently.
How it works
_ Push a copy of the string on the stack.
, Compute the length of the copy.
\ Swap the length and the original string.
"google"= Push 1 if the string is "google", 0 otherwise.
! Apply logical NOT. Maps 1 to 0 and 0 to 1.
/ Divide the length by the Boolean.
TSQL 2012, 87
CREATE FUNCTION g(@p CHAR(9))RETURNS INT AS BEGIN RETURN IIF(@p='google',@p,LEN(@p))END
How to use :
SELECT dbo.g('gogle')
-- return 5
SELECT dbo.g('google')
--return Conversion failed when converting the varchar value 'google ' to data type int.
C++, 81
int l(char *s){int b=0,i=0;do{b=s[i]^"google"[i]?1:b;}while(s[i++]);return--i/b;}
Divides by 0 on "google". This is my first C++ golf, so any tips would be welcome.
^ is used like !=. b is equal to 1 when the string is not "google", 0 if it is. So i/s will result in i/0.
Stuck, 16 Bytes
s_l1u"google"=-/
Following a similar method to most people, will cause a divide by 0 error on "google" being input.
ECMA6,30
g=(s)=>s=="google"?-1:s.length
Since a string length of -1 is an error I think this is a valid answer in Javascript (ECMA6).
I was initially inspired by the python trick of causing a division by zero mentioned near the top. However this does not work in Javascript because you can divide by zero and get "Infinity" without throwing an error so I looked into other options.
This works in Chrome you can copy this into the dev console and then run it by calling g("some string here"). I assume any other browser that has partial support for ECMA6 should be able to run it.
C, 66 48
Original:
int l(long*s){return strlen(s)/((*s&~(-1L<<56))!=0x656c676f6f67);}
Using OSX gcc,
l("duck"); returns 4,
l("google"); causes Floating point exception: 8.
On other platforms, the constants may need to be adjusted for endianness.
Shorter:
less trickyness, same results.
l(int*s){return strlen(s)/!!strcmp(s,"Google");}
Powershell, 60
$f={param([string]$s);if($s-eq'google'){throw $s};$s.Length}
Usage:
PS> & $f google
Throws an exception.
PS> & $f bing
Returns 4
Shortest I could come up with :(
JavaScript, 47 bytes
Nice and simple.
Edit: Now complies with the rules
function f(g){if(g=="google")a;return g.length}
Testing
Error thrown
function f(g){if(g=="google")a;return g.length}
alert(f("Hello"))
alert(f("google"))
alert(f("hi"))
No error thrown
function f(g){if(g=="google")a;return g.length}
alert(f("Hello"))
alert(f("bing"))
alert(f("hi"))
PowerShell, 42 bytes
function g($x){$x.Length/($x-ne'google')}
CoffeeScript, 32 bytes
g=(s)->(s if s!='google').length
To call:
g('bing') # returns 4
g('google') # TypeError: Cannot read property 'length' of undefined
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.
Scala, 36 34 30 29 characters
s=>(Set(s)-"google").max.size
Calling this function on "google" produces java.lang.UnsupportedOperationException: empty.max
bash, 55 51 34 bytes
Thanks @manatwork!
[ "$1" != google ]&&echo ${#1}||0
It prints command not found if $1 is google.
O, 20 characters
{."google"={@}{.e}?}
Sample run:
bash-4.3$ java xyz.jadonfowler.o.O <( echo '{."google"={@}{.e}?} :f "yahoo" f o' )
5
bash-4.3$ java xyz.jadonfowler.o.O <( echo '{."google"={@}{.e}?} :f "google" f o' )
java.lang.ArrayIndexOutOfBoundsException: Can't pop from empty stack!
at xyz.jadonfowler.o.Stack.pop(O.java:980)
at xyz.jadonfowler.o.O.parse(O.java:407)
at xyz.jadonfowler.o.CodeBlock.run(O.java:1031)
at xyz.jadonfowler.o.O.parse(O.java:735)
at xyz.jadonfowler.o.CodeBlock.run(O.java:1031)
at xyz.jadonfowler.o.O.parse(O.java:99)
at xyz.jadonfowler.o.O.runFile(O.java:37)
at xyz.jadonfowler.o.O.main(O.java:20)
java.lang.ArrayIndexOutOfBoundsException: Can't pop from empty stack!
at xyz.jadonfowler.o.Stack.pop(O.java:980)
at xyz.jadonfowler.o.O.parse(O.java:425)
at xyz.jadonfowler.o.O.runFile(O.java:37)
at xyz.jadonfowler.o.O.main(O.java:20)
C# 4.0, 51 bytes
int g(string s){return s.Length/(s!="google"?1:0);}
Sample:
string userInput = Console.ReadLine();
Console.WriteLine(g(userInput));
Output:
// "pogi" 4
// "google" DivideByZeroException was unhandled
PHP error via a warning(), 62, 52 46 bytes
I feel dirty for these, but it isn't about pretty:
function g($s){echo$s!=google?strlen($s):g();}
This will give "Warning: Missing argument 1 for g()" when you insert 'google', thought that was funny.
function g($s){echo$s!=google?strlen($s):die(err);}
function g($s){if($s!=google){return strlen($s);}die(error);}
PHP error as string, 46 bytes
function g($s){echo$s!=google?strlen($s):err;}
String dont have to be quoted (but should be!)
You can run these via the commandline using g($argv[1]);, or via an older PHP version's register_globals method as an GET g($_GET['string']) or whichever :)
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'])
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.
GolfScript, 14 16 Characters
{.,\'google'=!/}
Like many others, simply compares the input to 'google' and divides the length by the inverse of the result.
Example programs:
- With
'bing'(output:4) - With
'google'(output: Error: Attempted to divide by zero.)
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)}
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.
bash + coreutils, 57 49 38 36 33 bytes
[ "$1" = google ];expr ${#1} / $?
Calling it with google produces expr: division by zero.
The quotes around $1 are required in order to handle the empty string correctly.
The use of ${#1} is shamelessly stolen from Tarod's answer.
C - 99 75 67 63 bytes
g(char*s){int i=0,j=*s;while(s[i])j^=s[++i];return j^9?i:g(s);}
Ungolfed:
int g(char *s){
int i = 0,
j = s[0]; // first char of s
while(s[i] != '\0'){
j ^= s[++i]; // j = j XOR [next char]
}
if(j != 9){ // g^o^o^g^l^e = 9
return i;
} else {
g(s); // infinite recursion
}
}
Using it:
g("bing") // 4
g("duckduckgo") // 10
g("google") // segmentation fault
Will return the length if g XOR o XOR o XOR g XOR l XOR e isn't 9, else it will infinite recurse causing a stack overflow.
How it works
I used a (very) crappy hashing algorithm (a XOR b XOR c ...) to get a single number from the first six chars of the string. Collision likelyhood is very high, but if we assume the string has to be the name of an actual search engine, then the collision likelyhood is fairly low.
So, first we have i, which iterates through the string until s[i] is NUL (0), and while counting the length of the string, the selected char is XOR'd onto j, which is initialized to the first char in s. For "google", the result of this operation is 9.
The main thing this takes advantage of is the way pointers work in C. A pointer is actually a large number that denotes an address in memory, &var will return a pointer to var, while *var will dereference a pointer (grab the value at that address). Thus, *s is equivalent to s[0]. I think this is where most beginners get lost, confused and frustrated when it comes to C, like when you try to send a struct * to a function that takes struct * by sending &struct_ptr, which would be a memory address to a memory address, effectively making the compiler give an error such as function expects 'struct *' but got 'struct **'.
Haskell, 24 characters
g n|n/="google"=length n
"Unexhaustive patterns" if you pass it "google".
Javascript ES6, 51 27 25 bytes
Hi, I'm new to code golf so this can probably be golfed much more, but here it goes:
_=>_=="google"?a:_.length
g=_=>_=="google"?a:_.length
g=_=>{if("google"==_)throw Error();return _.length}
and some test:
(_=>_=="google"?a:_.length)("bing")//4
(_=>_=="google"?a:_.length)("google")// Error: a is not defined
g("bing")// returns 4
g("google")// Error: a is not defined
Edit: Added ? to replace if and replace Error with an undefined object.
Edit 2: I realized my byte count was wrong, and removed the g=
Scala, 48
def g(s:String)=if(s=="google")0/0 else s.length
To call:
g("bing") //> res1: Int = 4
g("google") //> java.lang.ArithmeticException: / by zero
C++11, 54 (code) + 14 (#include) = 68
Well, division by zero is just undefined behaviour, which I would not call an error. So my approach.
#include<ios>
[](std::string s){return s!="google"?s.size():throw;};
usage
[](std::string s){return s!="google"?s.size():throw;}("google");
Common Lisp, 50 48 bytes
(defun g(s)(if(equal s"google")(g s)(length s)))
Ungolfed:
(defun g(s) ; Define a function g with one argument s
(if (equal s "google") ; If s == "google",
(g s) ; Then recurse!
(length s) ; Else, return the length of s in characters
)
)
Defines a function g that accepts one string as input. If it is not exactly 'google', then it returns the length. Otherwise, it will call itself on the same string, creating an infinite recursive loop and eventually causing a stack overflow error.
Usage (inside an interactive CLISP shell):
>(load "google.lsp")
Finished loading.
>(g "foo")
3
>(g "Lisp is cool!")
13
>(g "google")
*** - Program stack overflow. RESET
This is pretty long compared to the others, but using recursion seemed fitting for Lisp.
PHP 5.4+, 40 49 bytes
This one is quite unexpectedly long.
function g($x){echo[strlen($x),[]][$x==google];}
To run it, just pass a value:
g($argv[1]);
Test-cases:
$php google.php googlea
7
$php google.php google
Notice: Array to string conversion in [...][...] on line 1
Array
I'm not sure if this can ve considered an error for this challenge or not.
One could use the over-used boring method:
function g($x){echo strlen($x)/$x==google;}
Which gives me a size of only 43 bytes.
As an alternative, one could use an exit error code, using the exit construct, for also 49 bytes:
function g($x){exit($x==google?strlen($x).'':1);}
All values between 1 and 254 are valid error codes that PHP uses when exiting.
rs, 31 bytes
^(google)|(.*)$/((^^\2))^^(1\1)
In rs, ^^ is the length and repetition operator. Used in the unary form, it will get the length of the following text (^^\2). Used in binary form, it will repeat the LHS RHS times ((^^\2))^^(1\1).
Take the input bing. The input is not google, so the second group will match, not the first. Once the substitutions take place, the result is ((^^bing))^^(1). ^^ gets the length to result in (4)^^(1), and the result gets repeated 1 time to result in 4.
However, if the input is google, the first group will match. That will result in ((^^))^^(1google) after substitutions. ^^ will just get the length of the empty string (0), so the result after ^^ is applied will be (0)^^(1google). Now the repetition operator can do its work...or not. See it will try to repeat 0 1google times. As 1google isn't a number, the output will be:
Traceback (most recent call last):
File "c callback", line 6, in <module>
File "<string>", line 5, in <module>
File "<string>", line 167, in main
File "<string>", line 125, in run
File "<string>", line 72, in expand
ValueError: invalid literal for int() with base 10: '1google'
Live demo. (Put the input text in the box at the bottom left.)
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.
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
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).
A 38 bytes PHP solution using division by zero:
<?=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.
Prolog – 32 bytes
"google"*_:-x.
X*Y:-length(X,Y).
Defines a predicate (*)/2 that throws ERROR: */2: Undefined procedure: x/0 for the input "google":
?- "bing" * Length.
Length = 4.
?- "google" * Length.
ERROR: */2: Undefined procedure: x/0
Exception: (8) x ? no debug
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
Java 7:53 52 Bytes
int g(String _){return"google"==_?0/0:_.length();}
Above code will throw ArithmeticException for division by zero and for any String other than google. Worth to note that == compares reference and won't work for String Objects.
Java 8 : 29 Bytes
(Based on suggestion given in below comment)
s->s=="google"?0/0:s.length()
APL, 19 17 bytes
{⍵≡'google':⍟⋄≢⍵}
This is an unnamed monadic function that will throw a syntax error if the input is google. This is accomplished by attempting to take the natural logarithm of nothing.
{
⍵≡'google': ⍝ If the right argument is "google"...
⍟⋄ ⍝ Compute log(<nothing>), which brings only sadness
≢⍵ ⍝ Otherwise compute the length
}
Saved two bytes thanks to Dennis!
Lua, 47 bytes
print(assert(arg[1]~="google")and arg[1]:len())
Throws "assertion failed" if it's "google"
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
><>, 55 bytes
i:0(?v
31&l~<v0"google"~~.?%2l
$v?(2l<S?*=2l=6:+={
&<;n
Figured I'd give this a go, not my best golfing attempt or algorithm, though. Not a function per se, but I think that this should still qualify. I'll see if I can edit in a better version.
If you're allowed to print the length and then error, here's a 46 byte solution:
i:0(?v
2lnl~<v0"google";?%
$;?(2l<S?*=2l=6:+={
49 byte previous solution of this nature:
i:0(?v
l0nl~<v;!?=7
:;?(2l<S?*=2l=6:+=@@g3
elgoog
I'm happy to put up an explanation if there's any interest, and please let me know if there's anything wrong with my answer or if you have golfing suggestions.
Haskell, 24 bytes
g s|s/="google"=length s
Output:
Main> g "google"
Program error: pattern match failure: g "google"
Main> g "bing"
4
Excel, 23 characters
Paste this into a cell other than A1 and type your search query into A1.
=LEN(A1)/(A1<>"google")
For example:
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
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]"}~}
Lua, 42 Bytes
This challenge has made me realize how hard it is to cause an error in Lua.
x=io.read()print(x~="google"and #x or t())
Takes an input and if that input isn't google than print the length of the input, if not call a function t which doesn't exist, throwing an error.
R, 46 bytes
g=function(x)ifelse(x!="google",nchar(x),)
Unless I'm misreading, the original post never specified that the code had to be correct syntax.
Example:
> g("bing")
[1] 4
> g("google")
Error in ifelse(x != "google", nchar(x), ) :
argument "no" is missing, with no default
I never added anything for the "no" parameter of the ifelse statement so it will return an error if this parameter is evoked.
STATA, 44 bytes
pr de a
if"google"==`0' f
di length(`0')
end
prints "unrecognized command: f" when input is "google"
Emacs Lisp, 43 bytes
(lambda(s)(if(equal s"google")*(length s)))
Throws the error (void-variable *) for any string that equals google.
Ruby, 34 30 27 26
->x{x=='google'?t: x.size}
Unknown t raises exception.
->x{x=='google'?fail():x.size}
Edit: totally readable and obvious version that is shorter...
->x{x[x=~/^(?!google$)/..-1].size}
Old: Pretty similar to other ideas it seems. Will raise ArgumentError if x is 'google'.
C# .NET, 65 bytes
int g(string s){return(s!="google")?s.Length:(1/int.Parse("0"));}
Test:
Console.WriteLine(g("str"));
Console.WriteLine(g("google"));
CoffeeScript 43 bytes
(g)->return g.length if g!="google";throw-1
Makes an anonymous function that throws -1 if the string is "google", and returns it's length otherwise. Not as obfuscated as I wanted, though.
Link to the online testing environment.
Another variation, 1 byte longer:
(g)->if g!="google"then g.length else throw-1
CoffeeScript, 36 bytes
f=(x)->throw 0if'google'==x;x.length
Python 3, 35 bytes
lambda n:len(n)if n!='google'else d
MUMPS, 28 bytes
g(s) q $S(s'="google":$L(s))
Usage:
>w $$g^MYROUTINE("bing")
4
>w $$g^MYROUTINE("google")
<SELECT>g^MYROUTINE
Why? Well, $S[ELECT] is basically a compact multi-clause if-else statement - almost like a pattern-match in a language like Haskell or Rust. Except... unlike in Haskell or Rust, the patterns aren't checked for exhaustiveness, because the notion of "compile-time safety" is completely alien to MUMPS. So if your input is a pattern you didn't account for, you get a lovely runtime error called <SELECT>.
Haskell - 30 characters
g"google"=error"!";g s=length s
>g "google"
*Exception: !
>g "str"
3




