# I'm a palindrome. Are you?

There have been a couple of previous attempts to ask this question, but neither conforms to modern standards on this site. Per discussion on Meta, I'm reposting it in a way that allows for fair competition under our modern rulesets.

## Background

A is a string that "reads the same forwards and backwards", i.e. the reverse of the string is the same as the string itself. We're not talking about "convenient palindromes" here, but a strict character-by-character reversal; for example, ()() is not a palindrome, but ())( is.

Write a program or function that takes a string S (or the appropriate equivalent in your language) as input, and has one output Q (of a type of your choice). You can use any reasonable means to take the input and provide the output.

• When the input S is a palindrome, the output Q should have a value A (that is the same for any palindromic S).
• When the input S is not a palindrome, the output Q should have a value B (that is the same for any non-palindromic S).
• A and B must be distinct from each other.

Or in other words: map all palindromes to one value, and all non-palindromes to another.

Additionally, the program or function you write must be a palindrome itself (i.e. its source code must be palindromic), making this a challenge.

## Clarifications

• Although true and false are obvious choices for A and B, you can use any two distinct values for your "is a palindrome" and "isn't a palindrome" outputs, which need not be booleans.
• We're defining string reversal at the character level here; éé is palindromic regardless of whether the program is encoded in UTF-8 or Latin-1, even though it's not a palindromic sequence of octets after UTF-8 encoding.
• However, even if your program contains non-ASCII characters, it only needs to work for ASCII input. Specifically, the input S will only contain printable ASCII characters (including space, but not including newline). Among other things, this means that if you treat the input as a sequence of bytes rather than a sequence of characters, your program will still likely comply with the specification (unless your language's I/O encoding is very weird). As such, the definition of a palindrome in the previous bullet only really matters when checking that the program has a correct form.
• Hiding half the program in a comment or string literal, while being uncreative, is legal; you're being scored on length, not creativity, so feel free to use "boring" methods to ensure your program is a palindrome. Of course, because you're being scored on length, parts of your program that don't do anything are going to worsen your score, so being able to use both halves of your program is likely going to be helpful if you can manage it.
• Because the victory criterion is measured in bytes, you'll need to specify the encoding in which your program is written to be able to score it (although in many cases it will be obvious which encoding you're using).

## Victory criterion

Even though the program needs to be a palindrome at the character level, we're using bytes to see who wins. Specifically, the shorter your program is, measured in bytes, the better; this is a challenge. In order to allow submissions (especially submissions in the same language) to be compared, place a byte count for your program in the header of your submission (plus a character count, if it differs from the number of bytes).

• Would someone please explain why would ()() not be a palindrome?? – Emilio M Bumachar Feb 20 '17 at 6:38
• @EmilioMBumachar Try replacing ( with a and ) with b. Is abab a palindrome? No, it would have to be abba. Then ()() isn't a palindrome either; it would have to be ())(. – DLosc Feb 20 '17 at 6:40
• Those solutions entirely using comments to make the program palindromic looks like a loophole to me :( – kennytm Feb 20 '17 at 8:26
• @kennytm Disallowing them would be worse, because there's no satisfactory way to do that objectively in a language-agnostic way. (What's a comment? What about putting the unused half in a string literal that is discarded? What about 2D languages where you can have perfectly executable code that is simply never reached?) – Martin Ender Feb 20 '17 at 9:08
• ()() is not a palindrome, but ())( is. Congratulations, you made it onto reddit! – numbermaniac Feb 25 '17 at 6:31

# Golfscript, 11 bytes

Bonus for the bytecount being a palindrome as well.

.-1%=#=%1-.


Duplicate, reverse, compare. Outputs 1 for palindromes and 0 for non-palindromes.

## QBIC, 17 bytes

;?A=_fA|#|Af_=A?;


Uses a boring comment-like ttrick to make the code a palindrome. Explanation:

;         Get a string literal from the cmd prompt
?         Print -1 for true and 0 for false in the following comparison
A=        Is A equal to
_fA|      A reversed?

#         Start a 'silent' string literal: This only forces the creation of string B
with the following text, but doesn't inject a reference to B$here. |Af_=A?; Code, reversed, as a string literal.  # AppleScript, 146 bytes clutch set x to(display dialog""default answer"")'s characters-- x=reverse of x--x fo esrever=x --sretcarahc s')""rewsna tluafed""golaid yalpsid(ot x tes  This should be fairly obvious. # Dyalog APL, 21 Bytes I decided to avoid a comment-based solution, and ended up with something pretty ugly. Instead of commenting out the second half of my code, I keep it in and allow the resulting syntax error to be part of my output. A←⍞⋄0∊A=⌽A⋄A⌽=A∊0⋄⍞←A  This prompts the user to enter a string, and prints 0 SYNTAX ERROR: The function requires a left argument A←⍞ ⋄ 0∊A=⌽A ⋄ A⌽=A∊0 ⋄ ⍞←A  If the input is a palindrome, and prints 1 SYNTAX ERROR: The function requires a left argument A←⍞ ⋄ 0∊A=⌽A ⋄ A⌽=A∊0 ⋄ ⍞←A  If the input is not a palindrome. A simple comment based solution would be to replace the middle character (⋄) with the comment symbol (⍝): A←⍞⋄0∊A=⌽A⍝A⌽=A∊0⋄⍞←A  This does the same as above but doesn't include the syntax error in the output. Here's an ungolfed version: A←⍞ ⍝ prompt user for input, store in variable A ⋄ ⍝ statement separator 0∊A=⌽A ⍝ return '0' if A is equal to A reversed (⌽A). Otherwise return '1' ⋄ ⍝ statement separator A⌽=A∊0⋄⍞←A ⍝ reverse of preceding code, throws a syntax error  # Common Lisp, 104 bytes (lambda(s)(format t"~:[F~;T~]"(equal(reverse s)s)));;)))s)s esrever(lauqe("]~T;~F[:~"t tamrof()s(adbmal(  Abusing idea for commenting out part of code from comments under question. # [Python], 84 bytes lambda s:list(s)==list(reversed(list(s)))#)))s(tsil(desrever(tsil==)s(tsil:s adbmal  Pretty simple, take the string s, convert it into a list of chars and then compare that against the reversed list of chars generated from the same string. • This answer is invalid because it isn't a palindrome itself. – DJMcMayhem Feb 20 '17 at 21:38 • @DJMcMayhem missed that caveat, but fixed now, unfortunately ugly. Helps clarify some of the other answers though ;P – sudobangbang Feb 20 '17 at 21:43 Javascript, 78 bytes (s=>s==s.split('').reverse().join(''))//))''(nioj.)(esrever.)''(tilps.s==s>=s(  This is the classic .split, .reverse and .join routine. Another (longer, but I like it more) 104 bytes solution would be (s=>!s.split('').find((a,i,l)=>a!==l[l.length-i-1]))//))]1-i-htgnel.l[l==!a>=)l,i,a((dnif.)''(tilps.s!>=s(  # Pyth - 3 bytes An alternative 3 byte solution. Palindromes give -1 and non-palindromes give 0. _q_  A few more 3 byte solutions: _/_ _}_  # Scala - 58 bytes def p(s:String)=s.reverse==s//s==esrever.s=)gnirtS:s(p fed  Example - p("abba") //returns true p("aabb") //returns false  # Java (with regex), 134 bytes s->s.matches("|(?:(.)(?<=(?=^.*?(\\1\\2?)$).*))+(?<=(?=^\\2$).*)")//)")*.)$2\\^=?(=<?(+))*.)$)?2\\1\\(?*.^=?(=<?().(:?(|"(sehctam.s>-s  Credits where due ## Testing import java.util.function.*; class Ideone { static Predicate<String> isPalindrome = s->s.matches("|(?:(.)(?<=(?=^.*?(\\1\\2?)$).*))+(?<=(?=^\\2$).*)")//)")*.)$2\\^=?(=<?(+))*.)$)?2\\1\\(?*.^=?(=<?().(:?(|"(sehctam.s>-s ; public static void main (String[] args) throws java.lang.Exception { testPalindrome("", true); testPalindrome("x", true); testPalindrome("xx", true); testPalindrome("xy", false); testPalindrome("xyx", true); testPalindrome("xxx", true); testPalindrome("xxyx", false); testPalindrome("racecar", true); testPalindrome("step on no pets", true); testPalindrome("aManaPlanaCanalPanaMa", true); testPalindrome("this is impossible", false); } static void testPalindrome(String s, boolean expected) { if (isPalindrome.test(s) == expected) { System.out.println("OK"); } else { System.out.printf("NOK: str=\"%s\", expected=%b%n", s, expected); } } }  Test it yourself! • This code is not a lambda expression. – Jakob Aug 30 '17 at 0:22 • @Jakob No? Why not? It works as a lambda, though. – Olivier Grégoire Aug 30 '17 at 5:39 • My complaint is with the comment. Seems to me that having anything outside the lambda expression makes it an invalid lambda solution. In particular, this solution cannot be embedded in a program the way a lambda expression can (e.g. with code appearing after it on the same line). See also the grammar for a lambda expression, which most lambda solutions adhere to, but this doesn't. – Jakob Aug 30 '17 at 20:41 • Why can't it be embedded? stream.map(a->a//comment<new_line>).collect(...) (replace <new_line> with an actual new line) works well! Just because 99.99% of lambdas adhere to that principle doesn't make this one invalid. Does it? A lambda isn't defined from how it appears in the source, but how it's compiled, and this one compiles just fine, unless proven otherwise. – Olivier Grégoire Aug 30 '17 at 21:02 • Well, my concern is not that it doesn't work or that it can't be embedded into a full program; it's that it violates the format of a lambda expression solution. I think I'll create a meta post where this discussion can continue. – Jakob Aug 30 '17 at 22:19 # Scala, 50 bytes Failed to not write a comment based solution so this is it: (s:String)=>s.reverse==s//s==esrever.s>=)gnirtS:s(  # Common Lisp, 61 bytes (lambda(n)(equal(reverse n)n));))n)n esrever(lauqe()n(adbmal(  Try it online! Outputs T when the string is palindrome, NIL otherwise. # Pyt, 1 byte ₽  Try it online!  implicit input ₽ palindromic test implicit output  ## Previous answer before I knew that 1 byte solutions were allowed ₽ƥƥ₽  Try it online! ₽ checks for palindromicness (is that a word?) ƥ prints the answer ƥ prints nothing ₽ checks the palindromicness of nothing • 1 byte. I don't think it ever says that solutions have to be more than a single byte. – caird coinheringaahing Jan 28 '18 at 21:09 • Oh that's weird. I could have sworn it did, but maybe it was a different challenge. – FantaC Jan 28 '18 at 21:10 # Japt, 2 bytes êê  Try it ê on its own in Japt creates a palindrome but, when passed a string as an argument (which the second ê is implicitly cast to in this case), it instead tests if a string is palindromic. # Add++, 13 bytes L,dbR=;=Rbd,L  Try it online! # C (gcc), 118 bytes Can sadly not come up with any solution without the boring comment approach. f(char*s){char*t=s+strlen(s);for(;*s&&*s++==*--t;);s=!*s;}//};s*!=s;);t--*==++s*&&s*;(rof;)s(nelrts+s=t*rahc{)s*rahc(f  Try it online! # Reflections, 125 bytes  _1=1\ /1#\ /+#_ >~< >~< (0//0) \ / >_ / _> / \ )0//0( <~> <~> _#+/ \#1/ \1=1_  Test it! Prints code point 0x04 as true, and nothing as false. There are a few spaces after some lines. ### Explanation The relevant part of the code is:  _1=1\ /1#\ /+#_ >~< >~< (0//0) \ / >_ /  • _ reads a line • 1=1 copies it to stack 1 • >~< creates a loop over the complete stack: • (0 pushes the top item to stack 0 • now stack 0 contains the reverse, and stack 1 the original • 1 moves stack 1 to mainstack • >~< loops again: • 0) takes the next character from reversed • >_ if original and reversed character are not equal: • end the program by navigating downwards, leaving the field • + produces the 4 • _ prints corresponding character • then the program stops (leaving the field to the right) The rest is only for palindromic source. I know this is boring. # Perl 5, 29 bytes $_=reverse=~$_#_$~=esrever=_$ Requres -p0. Outputs 1 if the input is a palindrome, empty otherwise. Try it online! Perl 5, 33 bytes +$_=reverse=~$_+q+_$~=esrever=_$+  Commentless version, requires -p0. Outputs 1 if the input is a palindrome, 0 otherwise. Try it online! # Ruby-n, 31 bytes p$_==$_.reverse#esrever._$==_$p  Try it online! A full program with implicit input (-n) turns out to be slightly shorter than lambda. # R, 71 bytes any(rev(x<-utf8ToInt(scan(,"")))-x)#)x-)))"",(nacs(tnIoT8ftu-<x(ver(yna  Try it online! Comments to make it a palindrome. Returns FALSE if the input is a palindrome, TRUE otherwise. Could save 2 bytes off the palindrome using sd if we were guaranteed to have an input size >1. Interpreting liberally this portion of the asnwer if you treat the input as a sequence of bytes rather than a sequence of characters, your program will still likely comply with the specification would lead to: ### R, 43 bytes any(x<-scan()-rev(x))#))x(ver-)(macs-<x(yna  Try it online! # Dyalog APL, 6 bytes ⌽≡⊢⊢≡⌽  Try it online! • This is the "correct" answer (as it works on all arrays), but for this particular challenge specification (argument is always a string), ⌷≡⌽⌽≡⌷ or +≡⌽⌽≡+ works too while also being visually palindromic. – Adám Feb 6 at 21:47 ## W, 3 bytes Pretty trivial, reverse & check equality & reciprocal. (I definitely beat Jelly by tying with Pyth.) ~=~  ## Explanation ~ Reverse the implicitly inputted string = Check whether this reversed string is equal to the original string ~ Find the reciprocal of this thing  # SmileBASIC, 109 bytes INPUT P$WHILE LEN(P$)>1P=P+(POP(P$)!=SHIFT(P$))WEND?!P'P!?DNEW))P$(TFIHS=!)$P(POP(+P==P1>)$P(NEL ELIHW$P TUPNI  Could definitely be shorter... # Perl 5, 69 bytes $_=<>;chop;print 1 if reverse eq$_#_$qe esrever fi 1 tnirp;pohc;><=_$ Takes input via STDIN. Prints 1 if the input is a palendrome, otherwise exits. • A couple of hints: you could save quite a few bytes by just printing the boolean returned by eq directly; and you could request input with no trailing newline to avoid the need to call chop. – user62131 Mar 28 '17 at 22:32 ## REXX, 78 bytes arg a b="say a=reverse(a)" interpret b exit tixe b terpretni ")a(esrever=a yas"=b a gra  I thought that early exit would leave the mirrored program uninterpreted, but at least Regina REXX complains about unbalanced parentheses, hence the INTERPRET workaround. # Kotlin, 32 bytes Just another "boring" solution but in Kotlin :)) s.reversed()==s//s==)(desrever.s  Try it online! # RProgN 2, 5 bytes ]iei]  Returns -1\n-1 for true, 0\n0 for false. ## Explained ]iei] ] # Duplicate the top of the stack. i # Reverse the duplicate e # Are they equal? 1 if true, 0 if false. i # Inverse calculates n*-1. Redunant. ] # Duplicate. Redundant.  Try it online! # BASH, 52 bytes [ "rev<<<$1" = "$1" ];$?$;] "1$" = "1$<<<ver" [  success output (run as palpal.bash: ~/workspace/golf$ bash palpal.bash "$(cat palpal.bash)" palpal.bash: line 1: 0$: command not found
palpal.bash: line 1: 1$: command not found palpal.bash: line 1: ]: command not found  failure output: ~/workspace/golf$ bash palpal.bash "hello"
palpal.bash: line 1: 1$: command not found palpal.bash: line 1: 1$: command not found


notice that first output line has either a 1 or 0 which are the return code of the actual palindrome check.

It's not much better than using a comment for the second half

# C++ (gcc), 138 bytes

[](auto s){return equal(s.begin(),s.begin()+s.size()/2,s.rbegin());}//};))(nigebr.s,2/)(ezis.s+)(nigeb.s,)(nigeb.s(lauqe nruter{)s otua(][


Lambda using a builtin to check if the argument is palindromic. To make it palindromic, I had to add the entire source, reversed, in a comment. Not very creative, I know. Note that clang will not compile this.

Try it online here.

# Gol><>, 31 bytes

iEv
?;>l2(q1h{-
-{h1q(2l>;?
vEi


Try it online!

iEv
?;>l2(q1h{-

iEv
i    Take input as a char
E   If the last input was EOF, pop and execute next; otherwise, skip 1
iEv  Take all input and move to next line

>l2(q1h{-?;
l2(         Is the stack length < 2? (1 if yes, 0 otherwise)
q        If not, skip 2 commands (consume the top)
1h      Print 1 and halt
{     Rotate the stack (bottom goes to the top)
-    Difference
?   If zero, skip one command (consume the top)
;  Halt without printing anything