Palindrome detection: Difference between revisions

Content added Content deleted
(Add Tailspin solution)
m (syntax highlighting fixup automation)
Line 30: Line 30:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F is_palindrome(s)
<syntaxhighlight lang="11l">F is_palindrome(s)
R s == reversed(s)</lang>
R s == reversed(s)</syntaxhighlight>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Reverse b string 25/06/2018
<syntaxhighlight lang="360asm">* Reverse b string 25/06/2018
PALINDRO CSECT
PALINDRO CSECT
USING PALINDRO,R13 base register
USING PALINDRO,R13 base register
Line 65: Line 65:
MSG DC CL23'IT IS A TRUE PALINDROME'
MSG DC CL23'IT IS A TRUE PALINDROME'
YREGS
YREGS
END PALINDRO</lang>
END PALINDRO</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 74: Line 74:
=={{header|8080 Assembly}}==
=={{header|8080 Assembly}}==


<lang 8080asm> org 100h
<syntaxhighlight lang="8080asm"> org 100h
jmp demo
jmp demo
;;; Is the $-terminated string at DE a palindrome?
;;; Is the $-terminated string at DE a palindrome?
Line 132: Line 132:
w2: db 'racecar$'
w2: db 'racecar$'
w3: db 'level$'
w3: db 'level$'
w4: db 'rosetta$'</lang>
w4: db 'rosetta$'</syntaxhighlight>


{{out}}
{{out}}
Line 142: Line 142:


=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==
<lang asm> cpu 8086
<syntaxhighlight lang="asm"> cpu 8086
org 100h
org 100h
section .text
section .text
Line 190: Line 190:
.w3: db 'level$'
.w3: db 'level$'
.w4: db 'redder$'
.w4: db 'redder$'
.w5: db 'rosetta$'</lang>
.w5: db 'rosetta$'</syntaxhighlight>


{{out}}
{{out}}
Line 201: Line 201:


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun reverse-split-at-r (xs i ys)
<syntaxhighlight lang="lisp">(defun reverse-split-at-r (xs i ys)
(if (zp i)
(if (zp i)
(mv xs ys)
(mv xs ys)
Line 217: Line 217:
(if (= (mod lngth 2) 1)
(if (= (mod lngth 2) 1)
(equal (rest xs) ys)
(equal (rest xs) ys)
(equal xs ys)))))</lang>
(equal xs ys)))))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>BYTE FUNC Palindrome(CHAR ARRAY s)
<syntaxhighlight lang="action!">BYTE FUNC Palindrome(CHAR ARRAY s)
BYTE l,r
BYTE l,r


Line 287: Line 287:
Test("This sentence is not a palindrome.")
Test("This sentence is not a palindrome.")
Test("123 456 789 897 654 321")
Test("123 456 789 897 654 321")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Palindrome_detection.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Palindrome_detection.png Screenshot from Atari 8-bit computer]
Line 306: Line 306:
=={{header|ActionScript}}==
=={{header|ActionScript}}==
The following function handles non-ASCII characters properly, since charAt() returns a single Unicode character.
The following function handles non-ASCII characters properly, since charAt() returns a single Unicode character.
<lang ActionScript>function isPalindrome(str:String):Boolean
<syntaxhighlight lang="actionscript">function isPalindrome(str:String):Boolean
{
{
for(var first:uint = 0, second:uint = str.length - 1; first < second; first++, second--)
for(var first:uint = 0, second:uint = str.length - 1; first < second; first++, second--)
if(str.charAt(first) != str.charAt(second)) return false;
if(str.charAt(first) != str.charAt(second)) return false;
return true;
return true;
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>function Palindrome (Text : String) return Boolean is
<syntaxhighlight lang="ada">function Palindrome (Text : String) return Boolean is
begin
begin
for Offset in 0..Text'Length / 2 - 1 loop
for Offset in 0..Text'Length / 2 - 1 loop
Line 322: Line 322:
end loop;
end loop;
return True;
return True;
end Palindrome;</lang>
end Palindrome;</syntaxhighlight>


----
----
Ada 2012 version:
Ada 2012 version:
<lang ada>
<syntaxhighlight lang="ada">
function Palindrome (Text : String) return Boolean is
function Palindrome (Text : String) return Boolean is
(for all i in Text'Range => Text(i)= Text(Text'Last-i+Text'First));
(for all i in Text'Range => Text(i)= Text(Text'Last-i+Text'First));
</syntaxhighlight>
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 337: Line 337:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - except for the '''FORMAT''' and ''printf'' in test}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - except for the '''FORMAT''' and ''printf'' in test}}
<lang algol68># Iterative #
<syntaxhighlight lang="algol68"># Iterative #
PROC palindrome = (STRING s)BOOL:(
PROC palindrome = (STRING s)BOOL:(
FOR i TO UPB s OVER 2 DO
FOR i TO UPB s OVER 2 DO
Line 362: Line 362:
printf((template, t, palindrome(t)));
printf((template, t, palindrome(t)));
printf((template, t, palindrome r(t)))
printf((template, t, palindrome r(t)))
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 371: Line 371:
=={{header|APL}}==
=={{header|APL}}==
NARS2000 APL, dynamic function "if the argument matches the reverse of the argument", with Unicode character support:
NARS2000 APL, dynamic function "if the argument matches the reverse of the argument", with Unicode character support:
<lang APL> {⍵≡⌽⍵} 'abc'
<syntaxhighlight lang="apl"> {⍵≡⌽⍵} 'abc'
0
0
{⍵≡⌽⍵} '⍋racecar⍋'
{⍵≡⌽⍵} '⍋racecar⍋'
1</lang>
1</syntaxhighlight>
Or in tacit function form, a combination of three functions, right tack (echo), reverse, then the result of each compared with the middle one, match (equals):
Or in tacit function form, a combination of three functions, right tack (echo), reverse, then the result of each compared with the middle one, match (equals):
<lang APL> (⊢≡⌽) 'abc'
<syntaxhighlight lang="apl"> (⊢≡⌽) 'abc'
0
0
(⊢≡⌽) 'nun'
(⊢≡⌽) 'nun'
1</lang>
1</syntaxhighlight>
An inexact version is harder, because uppercase and lowercase with Unicode awareness depends on APL interpreter; NARS2000 has no support for it. Classic case conversion means lookup up the letters in an alphabet of UppercaseLowercase, then mapping those positions into an UppercaseUppercase or LowercaseLowercase array. Remove non-A-Za-z first to get rid of punctuation, and get an inexact dynamic function with just English letter support:
An inexact version is harder, because uppercase and lowercase with Unicode awareness depends on APL interpreter; NARS2000 has no support for it. Classic case conversion means lookup up the letters in an alphabet of UppercaseLowercase, then mapping those positions into an UppercaseUppercase or LowercaseLowercase array. Remove non-A-Za-z first to get rid of punctuation, and get an inexact dynamic function with just English letter support:
<lang APL>inexact←{Aa←(⎕A,⎕a) ⋄ (⊢≡⌽)(⎕a,⎕a)[Aa⍳⍵/⍨⍵∊Aa]}
<syntaxhighlight lang="apl">inexact←{Aa←(⎕A,⎕a) ⋄ (⊢≡⌽)(⎕a,⎕a)[Aa⍳⍵/⍨⍵∊Aa]}
inexact 'abc,-cbA2z'
inexact 'abc,-cbA2z'
0
0
inexact 'abc,-cbA2'
inexact 'abc,-cbA2'
1</lang>
1</syntaxhighlight>
Dyalog APL has a Unicode-aware uppercase/lowercase function (819 I-beam), AFAIK no support for looking up Unicode character classes.
Dyalog APL has a Unicode-aware uppercase/lowercase function (819 I-beam), AFAIK no support for looking up Unicode character classes.


Line 391: Line 391:


Using post-Yosemite AppleScript (to pull in lowercaseStringWithLocale from Foundation classes)
Using post-Yosemite AppleScript (to pull in lowercaseStringWithLocale from Foundation classes)
<lang AppleScript>use framework "Foundation"
<syntaxhighlight lang="applescript">use framework "Foundation"


------ CASE-INSENSITIVE PALINDROME, IGNORING SPACES ? ----
------ CASE-INSENSITIVE PALINDROME, IGNORING SPACES ? ----
Line 465: Line 465:
((ca's NSString's stringWithString:(str))'s ¬
((ca's NSString's stringWithString:(str))'s ¬
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower</lang>
end toLower</syntaxhighlight>
{{Out}}
{{Out}}
<pre>true</pre>
<pre>true</pre>
Line 471: Line 471:
===Core language only===
===Core language only===
It's not clear if "sequence of characters" means an array thereof or a single piece of text. But the basic method in AppleScript would be:
It's not clear if "sequence of characters" means an array thereof or a single piece of text. But the basic method in AppleScript would be:
<lang applescript>on isPalindrome(txt)
<syntaxhighlight lang="applescript">on isPalindrome(txt)
set txt to join(txt, "") -- In case the input's a list (array).
set txt to join(txt, "") -- In case the input's a list (array).
return (txt = join(reverse of txt's characters, ""))
return (txt = join(reverse of txt's characters, ""))
Line 484: Line 484:
end join
end join


return isPalindrome("Radar")</lang>
return isPalindrome("Radar")</syntaxhighlight>


Text comparisons in AppleScript are case-insensitive by default, so:
Text comparisons in AppleScript are case-insensitive by default, so:


{{output}}
{{output}}
<lang applescript>true</lang>
<syntaxhighlight lang="applescript">true</syntaxhighlight>


If case is to be taken into account, the call to the handler can be enclosed in a 'considering case' control statement.
If case is to be taken into account, the call to the handler can be enclosed in a 'considering case' control statement.
<lang applescript>considering case
<syntaxhighlight lang="applescript">considering case
return isPalindrome("Radar")
return isPalindrome("Radar")
end considering</lang>
end considering</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>false</lang>
<syntaxhighlight lang="applescript">false</syntaxhighlight>


It's also possible to "ignore" white space, hyphens, and punctuation, which are considered by default. And of course case can be ignored explicitly, if desired, to ensure that this condition's in force during the call to the handler. The attributes can be combined in one statement. So to check for inexact palindromicity (if that's a word):
It's also possible to "ignore" white space, hyphens, and punctuation, which are considered by default. And of course case can be ignored explicitly, if desired, to ensure that this condition's in force during the call to the handler. The attributes can be combined in one statement. So to check for inexact palindromicity (if that's a word):


<lang applescript>ignoring case, white space, hyphens and punctuation
<syntaxhighlight lang="applescript">ignoring case, white space, hyphens and punctuation
return isPalindrome("Was it a 😀car, or a c😀at-I-saw?")
return isPalindrome("Was it a 😀car, or a c😀at-I-saw?")
end ignoring</lang>
end ignoring</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>true</lang>
<syntaxhighlight lang="applescript">true</syntaxhighlight>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<lang ApplesoftBasic>100 DATA"MY DOG HAS FLEAS"
<syntaxhighlight lang="applesoftbasic">100 DATA"MY DOG HAS FLEAS"
110 DATA"MADAM, I'M ADAM."
110 DATA"MADAM, I'M ADAM."
120 DATA"1 ON 1"
120 DATA"1 ON 1"
Line 534: Line 534:
350 PA = MID$(W$, L0, 1) = MID$(W$, L - L0 + 1, 1)
350 PA = MID$(W$, L0, 1) = MID$(W$, L - L0 + 1, 1)
360 IF PALINDROME THEN NEXT L0
360 IF PALINDROME THEN NEXT L0
370 RETURN</lang>
370 RETURN</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
<lang>@ Check whether the ASCII string in [r0] is a palindrome
<syntaxhighlight lang="text">@ Check whether the ASCII string in [r0] is a palindrome
@ Returns with zero flag set if palindrome.
@ Returns with zero flag set if palindrome.
palin: mov r1,r0 @ Find end of string
palin: mov r1,r0 @ Find end of string
Line 590: Line 590:
w4: .asciz "redder"
w4: .asciz "redder"
w5: .asciz "rosetta"
w5: .asciz "rosetta"
words: .word w1,w2,w3,w4,w5,0</lang>
words: .word w1,w2,w3,w4,w5,0</syntaxhighlight>


{{out}}
{{out}}
Line 601: Line 601:


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>palindrome?: $[seq] -> seq = reverse seq
<syntaxhighlight lang="rebol">palindrome?: $[seq] -> seq = reverse seq
loop ["abba" "boom" "radar" "civic" "great"] 'wrd [
loop ["abba" "boom" "radar" "civic" "great"] 'wrd [
print [wrd ": palindrome?" palindrome? wrd]
print [wrd ": palindrome?" palindrome? wrd]
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 617: Line 617:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Reversing the string:
Reversing the string:
<lang AutoHotkey>IsPalindrome(Str){
<syntaxhighlight lang="autohotkey">IsPalindrome(Str){
Loop, Parse, Str
Loop, Parse, Str
ReversedStr := A_LoopField . ReversedStr
ReversedStr := A_LoopField . ReversedStr
return, (ReversedStr == Str)?"Exact":(RegExReplace(ReversedStr,"\W")=RegExReplace(Str,"\W"))?"Inexact":"False"
return, (ReversedStr == Str)?"Exact":(RegExReplace(ReversedStr,"\W")=RegExReplace(Str,"\W"))?"Inexact":"False"
}</lang>
}</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==


<lang AutoIt>;== AutoIt Version: 3.3.8.1
<syntaxhighlight lang="autoit">;== AutoIt Version: 3.3.8.1


Global $aString[7] = [ _
Global $aString[7] = [ _
Line 656: Line 656:
Return True
Return True
EndFunc
EndFunc
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<syntaxhighlight lang="text">
<lang Text>
"In girum imus nocte, et consumimur igni" is an inexact palindrome.
"In girum imus nocte, et consumimur igni" is an inexact palindrome.
"Madam, I'm Adam." is an inexact palindrome.
"Madam, I'm Adam." is an inexact palindrome.
Line 666: Line 666:
"Ein Neger mit Gazelle zagt im Regen nie." is an inexact palindrome.
"Ein Neger mit Gazelle zagt im Regen nie." is an inexact palindrome.
"something wrong" is not a palindrome.
"something wrong" is not a palindrome.
</syntaxhighlight>
</lang>


--[[User:BugFix|BugFix]] ([[User talk:BugFix|talk]]) 14:26, 13 November 2013 (UTC)
--[[User:BugFix|BugFix]] ([[User talk:BugFix|talk]]) 14:26, 13 November 2013 (UTC)
Line 675: Line 675:
See [[Reversing a string]].
See [[Reversing a string]].


<lang awk>function is_palindro(s)
<syntaxhighlight lang="awk">function is_palindro(s)
{
{
if ( s == reverse(s) ) return 1
if ( s == reverse(s) ) return 1
return 0
return 0
}</lang>
}</syntaxhighlight>


'''Recursive'''
'''Recursive'''


<lang awk>function is_palindro_r(s)
<syntaxhighlight lang="awk">function is_palindro_r(s)
{
{
if ( length(s) < 2 ) return 1
if ( length(s) < 2 ) return 1
if ( substr(s, 1, 1) != substr(s, length(s), 1) ) return 0
if ( substr(s, 1, 1) != substr(s, length(s), 1) ) return 0
return is_palindro_r(substr(s, 2, length(s)-2))
return is_palindro_r(substr(s, 2, length(s)-2))
}</lang>
}</syntaxhighlight>


'''Testing'''
'''Testing'''
<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
pal = "ingirumimusnocteetconsumimurigni"
pal = "ingirumimusnocteetconsumimurigni"
print is_palindro(pal)
print is_palindro(pal)
print is_palindro_r(pal)
print is_palindro_r(pal)
}</lang>
}</syntaxhighlight>


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang freebasic>
<syntaxhighlight lang="freebasic">
OPTION COMPARE TRUE
OPTION COMPARE TRUE


Line 710: Line 710:
PRINT "Not a palindrome."
PRINT "Not a palindrome."
ENDIF
ENDIF
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 724: Line 724:


=={{header|Bash}}==
=={{header|Bash}}==
<lang bash>
<syntaxhighlight lang="bash">
#! /bin/bash
#! /bin/bash
# very simple way to detect a palindrome in Bash
# very simple way to detect a palindrome in Bash
Line 755: Line 755:
echo "$input is a palindrome"
echo "$input is a palindrome"
fi
fi
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QBasic}}
{{works with|QBasic}}


<lang qbasic>' OPTION _EXPLICIT ' For QB64. In VB-DOS remove the underscore.
<syntaxhighlight lang="qbasic">' OPTION _EXPLICIT ' For QB64. In VB-DOS remove the underscore.


DIM txt$
DIM txt$
Line 839: Line 839:
RvrsText$ = NewText$
RvrsText$ = NewText$


END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


{{out}}
{{out}}
Line 853: Line 853:


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">
<lang IS-BASIC>
100 PROGRAM "Palindr.bas"
100 PROGRAM "Palindr.bas"
110 LINE INPUT PROMPT "Text: ":TX$
110 LINE INPUT PROMPT "Text: ":TX$
Line 874: Line 874:
280 IF TX$(I)<>TX$(LEN(TX$)-I+1) THEN LET PALIND=0:EXIT FOR
280 IF TX$(I)<>TX$(LEN(TX$)-I+1) THEN LET PALIND=0:EXIT FOR
290 NEXT
290 NEXT
300 END DEF</lang>
300 END DEF</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
====Exact palindrome====
====Exact palindrome====
The specification suggests, but does not insist, that we reverse the input string and then test for equality; this algorithm is more efficient.
The specification suggests, but does not insist, that we reverse the input string and then test for equality; this algorithm is more efficient.
<lang basic> 10 INPUT S$
<syntaxhighlight lang="basic"> 10 INPUT S$
20 FOR I=1 TO LEN S$/2
20 FOR I=1 TO LEN S$/2
30 IF S$(I)<>S$(LEN S$-I+1) THEN GOTO 60
30 IF S$(I)<>S$(LEN S$-I+1) THEN GOTO 60
Line 885: Line 885:
50 GOTO 70
50 GOTO 70
60 PRINT "NOT A ";
60 PRINT "NOT A ";
70 PRINT "PALINDROME"</lang>
70 PRINT "PALINDROME"</syntaxhighlight>
====Inexact palindrome====
====Inexact palindrome====
Add the following lines to convert the program into an inexact-palindrome checker (i.e. one that ignores non-alphabetic characters). The resulting program still works with only 1k of RAM. The ZX81 only supports its own character set, which does not include lower case, so that case-insensitive comparison and <i>a fortiori</i> Unicode are not possible.
Add the following lines to convert the program into an inexact-palindrome checker (i.e. one that ignores non-alphabetic characters). The resulting program still works with only 1k of RAM. The ZX81 only supports its own character set, which does not include lower case, so that case-insensitive comparison and <i>a fortiori</i> Unicode are not possible.
<lang basic> 15 GOSUB 90
<syntaxhighlight lang="basic"> 15 GOSUB 90
80 STOP
80 STOP
90 LET T$=""
90 LET T$=""
Line 895: Line 895:
120 NEXT I
120 NEXT I
130 LET S$=T$
130 LET S$=T$
140 RETURN</lang>
140 RETURN</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic> test$ = "A man, a plan, a canal: Panama!"
<syntaxhighlight lang="bbcbasic"> test$ = "A man, a plan, a canal: Panama!"
PRINT """" test$ """" ;
PRINT """" test$ """" ;
IF FNpalindrome(FNletters(test$)) THEN
IF FNpalindrome(FNletters(test$)) THEN
Line 924: Line 924:
ENDIF
ENDIF
NEXT
NEXT
= B$</lang>
= B$</syntaxhighlight>
{{out}}
{{out}}
<pre>"A man, a plan, a canal: Panama!" is a palindrome</pre>
<pre>"A man, a plan, a canal: Panama!" is a palindrome</pre>
Line 930: Line 930:
=={{header|Batch File}}==
=={{header|Batch File}}==


<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion
set /p string=Your string :
set /p string=Your string :
Line 944: Line 944:
echo %string% %palindrome% a palindrome.
echo %string% %palindrome% a palindrome.
pause
pause
exit</lang>
exit</syntaxhighlight>


Or, recursive (and without setlocal enabledelayedexpansion) (compatible with ReactOS cmd.exe)
Or, recursive (and without setlocal enabledelayedexpansion) (compatible with ReactOS cmd.exe)
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
set /p testString=Your string (all same case please) :
set /p testString=Your string (all same case please) :
call :isPalindrome result %testString: =%
call :isPalindrome result %testString: =%
Line 965: Line 965:
call :isPalindrome %1 %string:~1,-1%
call :isPalindrome %1 %string:~1,-1%
)
)
goto :eof</lang>
goto :eof</syntaxhighlight>


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


let palindrome(s) = valof
let palindrome(s) = valof
Line 1,010: Line 1,010:
for i = 0 to 8 do
for i = 0 to 8 do
writef("'%S': %S*N", tests!i, check(tests!i))
writef("'%S': %S*N", tests!i, check(tests!i))
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>'rotor': exact palindrome
<pre>'rotor': exact palindrome
Line 1,027: Line 1,027:


The following code reads a line from stdin and prints "True" if it is a palindrome, or False" otherwise.
The following code reads a line from stdin and prints "True" if it is a palindrome, or False" otherwise.
<lang befunge>v_$0:8p>:#v_:18p08g1-08p >:08g`!v
<syntaxhighlight lang="befunge">v_$0:8p>:#v_:18p08g1-08p >:08g`!v
~->p5p ^ 0v1p80-1g80vj!-g5g80g5_0'ev
~->p5p ^ 0v1p80-1g80vj!-g5g80g5_0'ev
:a^80+1:g8<>8g1+:18pv>0"eslaF">:#,_@
:a^80+1:g8<>8g1+:18pv>0"eslaF">:#,_@
[[relet]]-2010------>003-x -^"Tru"<</lang>
[[relet]]-2010------>003-x -^"Tru"<</syntaxhighlight>


{{works with|Befunge|93}}
{{works with|Befunge|93}}
Line 1,041: Line 1,041:
* The potential palindrome can be no longer than 76 characters (which beats the previous version's 11), and ''everything'' (spaces, punctuation, capitalization, etc.) is considered part of the palindrome. (Best to just use lower case letters and ''nothing else''.)
* The potential palindrome can be no longer than 76 characters (which beats the previous version's 11), and ''everything'' (spaces, punctuation, capitalization, etc.) is considered part of the palindrome. (Best to just use lower case letters and ''nothing else''.)


<lang befunge>v> "emordnilap a toN",,,,,,,,,,,,,,,,@,,,,,,,,,,,,,,,"Is a palindrome" <
<syntaxhighlight lang="befunge">v> "emordnilap a toN",,,,,,,,,,,,,,,,@,,,,,,,,,,,,,,,"Is a palindrome" <
2^ < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < <
2^ < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < <
4 ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v
4 ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v ^_v
Line 1,058: Line 1,058:
>09g8p09g1+09pv
>09g8p09g1+09pv
|: < <
|: < <
^<</lang>
^<</syntaxhighlight>


=={{header|BQN}}==
=={{header|BQN}}==
Line 1,065: Line 1,065:
BQN considers characters as single units, and hence the functions support unicode by default.
BQN considers characters as single units, and hence the functions support unicode by default.


<lang bqn>Pal ← ≡⊸⌽
<syntaxhighlight lang="bqn">Pal ← ≡⊸⌽
Pal1 ← ⊢≡⌽
Pal1 ← ⊢≡⌽
Pal2 ← {𝕩≡⌽𝕩}</lang>
Pal2 ← {𝕩≡⌽𝕩}</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( ( palindrome
<syntaxhighlight lang="bracmat">( ( palindrome
= a
= a
. @(!arg:(%?a&utf$!a) ?arg !a)
. @(!arg:(%?a&utf$!a) ?arg !a)
Line 1,103: Line 1,103:
)
)
&
&
);</lang>
);</syntaxhighlight>
Output:
Output:
<pre>In girum imus nocte et consumimur igni is indeed a palindrome
<pre>In girum imus nocte et consumimur igni is indeed a palindrome
Line 1,119: Line 1,119:
=={{header|Burlesque}}==
=={{header|Burlesque}}==


<lang burlesque>
<syntaxhighlight lang="burlesque">
zz{ri}f[^^<-==
zz{ri}f[^^<-==
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
Line 1,132: Line 1,132:
and if the length is odd, the middle doesn't need to be checked (so it's okay to do integer division by 2, which rounds down).
and if the length is odd, the middle doesn't need to be checked (so it's okay to do integer division by 2, which rounds down).


<lang c>#include <string.h>
<syntaxhighlight lang="c">#include <string.h>


int palindrome(const char *s)
int palindrome(const char *s)
Line 1,143: Line 1,143:
}
}
return 1;
return 1;
}</lang>
}</syntaxhighlight>
More idiomatic version:
More idiomatic version:
<lang c>int palindrome(const char *s)
<syntaxhighlight lang="c">int palindrome(const char *s)
{
{
const char *t; /* t is a pointer that traverses backwards from the end */
const char *t; /* t is a pointer that traverses backwards from the end */
Line 1,154: Line 1,154:
}
}
return 1;
return 1;
}</lang>
}</syntaxhighlight>


'''Recursive'''
'''Recursive'''
Line 1,161: Line 1,161:
itself a palindrome.
itself a palindrome.


<lang c>int palindrome_r(const char *s, int b, int e)
<syntaxhighlight lang="c">int palindrome_r(const char *s, int b, int e)
{
{
if ( (e - 1) <= b ) return 1;
if ( (e - 1) <= b ) return 1;
if ( s[b] != s[e-1] ) return 0;
if ( s[b] != s[e-1] ) return 0;
return palindrome_r(s, b+1, e-1);
return palindrome_r(s, b+1, e-1);
}</lang>
}</syntaxhighlight>


'''Testing'''
'''Testing'''


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <string.h>
/* testing */
/* testing */
Line 1,184: Line 1,184:
t, palindrome_r(t, 0, l) ? "" : "n't");
t, palindrome_r(t, 0, l) ? "" : "n't");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 1,190: Line 1,190:
'''Non-recursive'''
'''Non-recursive'''


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


class Program
class Program
Line 1,210: Line 1,210:
Console.WriteLine(IsPalindrome("ingirumimusnocteetconsumimurigni"));
Console.WriteLine(IsPalindrome("ingirumimusnocteetconsumimurigni"));
}
}
}</lang>
}</syntaxhighlight>


'''Using LINQ operators'''
'''Using LINQ operators'''
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;


Line 1,228: Line 1,228:
}
}
}
}
</syntaxhighlight>
</lang>


'''No string reversal'''
'''No string reversal'''


Reversing a string is very slow. A much faster way is to simply compare characters.
Reversing a string is very slow. A much faster way is to simply compare characters.
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


static class Program
static class Program
Line 1,249: Line 1,249:
Console.WriteLine("ingirumimusnocteetconsumimurigni".IsPalindrome());
Console.WriteLine("ingirumimusnocteetconsumimurigni".IsPalindrome());
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
The C solutions also work in C++, but C++ allows a simpler one:
The C solutions also work in C++, but C++ allows a simpler one:
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <algorithm>
#include <algorithm>


Line 1,259: Line 1,259:
{
{
return std::equal(s.begin(), s.end(), s.rbegin());
return std::equal(s.begin(), s.end(), s.rbegin());
}</lang>
}</syntaxhighlight>


Or, checking half is sufficient (on odd-length strings, this will ignore the middle element):
Or, checking half is sufficient (on odd-length strings, this will ignore the middle element):
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <algorithm>
#include <algorithm>


Line 1,268: Line 1,268:
{
{
return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn palindrome? [s]
<syntaxhighlight lang="clojure">(defn palindrome? [s]
(= s (clojure.string/reverse s)))</lang>
(= s (clojure.string/reverse s)))</syntaxhighlight>


'''lower-level, but somewhat faster'''
'''lower-level, but somewhat faster'''
<lang clojure>(defn palindrome? [^String s]
<syntaxhighlight lang="clojure">(defn palindrome? [^String s]
(loop [front 0 back (dec (.length s))]
(loop [front 0 back (dec (.length s))]
(or (>= front back)
(or (>= front back)
(and (= (.charAt s front) (.charAt s back))
(and (= (.charAt s front) (.charAt s back))
(recur (inc front) (dec back)))))</lang>
(recur (inc front) (dec back)))))</syntaxhighlight>


'''Test'''
'''Test'''
Line 1,290: Line 1,290:


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% Reverse a string
<syntaxhighlight lang="clu">% Reverse a string
str_reverse = proc (s: string) returns (string)
str_reverse = proc (s: string) returns (string)
chs: array[char] := array[char]$predict(0, string$size(s))
chs: array[char] := array[char]$predict(0, string$size(s))
Line 1,343: Line 1,343:
end
end
end
end
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>"rotor": exact palindrome
<pre>"rotor": exact palindrome
Line 1,356: Line 1,356:
=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
{{works with|GnuCOBOL}}
<lang COBOL> identification division.
<syntaxhighlight lang="cobol"> identification division.
function-id. palindromic-test.
function-id. palindromic-test.


Line 1,375: Line 1,375:
goback.
goback.
end function palindromic-test.
end function palindromic-test.
</syntaxhighlight>
</lang>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
String::isPalindrome = ->
String::isPalindrome = ->
for i in [0...@length / 2] when @[i] isnt @[@length - (i + 1)]
for i in [0...@length / 2] when @[i] isnt @[@length - (i + 1)]
Line 1,391: Line 1,391:
'There is no spoon.'
'There is no spoon.'
]
]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,399: Line 1,399:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun palindrome-p (s)
<syntaxhighlight lang="lisp">(defun palindrome-p (s)
(string= s (reverse s)))</lang>
(string= s (reverse s)))</syntaxhighlight>
===Alternate solution===
===Alternate solution===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]


<lang lisp>
<syntaxhighlight lang="lisp">
;; Project : Palindrome detection
;; Project : Palindrome detection


Line 1,418: Line 1,418:
(palindrome x)
(palindrome x)
(terpri)
(terpri)
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,427: Line 1,427:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE BbtPalindrome;
MODULE BbtPalindrome;
IMPORT StdLog;
IMPORT StdLog;
Line 1,464: Line 1,464:
END Do;
END Do;
END BbtPalindrome.
END BbtPalindrome.
</syntaxhighlight>
</lang>
Execute: ^Q BbtPalindrome.Do<br/>
Execute: ^Q BbtPalindrome.Do<br/>
{{out}}
{{out}}
Line 1,474: Line 1,474:


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


# Check if a string is a palindrome
# Check if a string is a palindrome
Line 1,543: Line 1,543:
end if;
end if;
i := i + 1;
i := i + 1;
end loop;</lang>
end loop;</syntaxhighlight>


{{out}}
{{out}}
Line 1,557: Line 1,557:
=={{header|Crystal}}==
=={{header|Crystal}}==
===Declarative===
===Declarative===
<syntaxhighlight lang="ruby">
<lang Ruby>
def palindrome(s)
def palindrome(s)
s == s.reverse
s == s.reverse
end
end
</syntaxhighlight>
</lang>


===Imperative===
===Imperative===
<syntaxhighlight lang="ruby">
<lang Ruby>
def palindrome_imperative(s) : Bool
def palindrome_imperative(s) : Bool
mid = s.size // 2
mid = s.size // 2
Line 1,576: Line 1,576:
true
true
end
end
</syntaxhighlight>
</lang>


Also
Also


<lang Ruby>def palindrome_2(s)
<syntaxhighlight lang="ruby">def palindrome_2(s)
mid = s.size // 2
mid = s.size // 2
mid.times { |j| return false if s[j] != s[-1 - j] }
mid.times { |j| return false if s[j] != s[-1 - j] }
true
true
end</lang>
end</syntaxhighlight>


Performance comparison
Performance comparison
<syntaxhighlight lang="ruby">
<lang Ruby>
require "benchmark"
require "benchmark"
Benchmark.ips do |x|
Benchmark.ips do |x|
Line 1,594: Line 1,594:
x.report("imperative2") { palindrome_2("hannah")}
x.report("imperative2") { palindrome_2("hannah")}
end
end
</syntaxhighlight>
</lang>


<pre>declarative 45.45M ( 22.00ns) (±11.16%) 32.0B/op fastest
<pre>declarative 45.45M ( 22.00ns) (±11.16%) 32.0B/op fastest
Line 1,602: Line 1,602:
=={{header|D}}==
=={{header|D}}==
===High-level 32-bit Unicode Version===
===High-level 32-bit Unicode Version===
<lang d>import std.traits, std.algorithm;
<syntaxhighlight lang="d">import std.traits, std.algorithm;


bool isPalindrome1(C)(in C[] s) pure /*nothrow*/
bool isPalindrome1(C)(in C[] s) pure /*nothrow*/
Line 1,623: Line 1,623:
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("salàlas"));
assert(pali("salàlas"));
}</lang>
}</syntaxhighlight>


===Mid-level 32-bit Unicode Version===
===Mid-level 32-bit Unicode Version===
<lang d>import std.traits;
<syntaxhighlight lang="d">import std.traits;


bool isPalindrome2(C)(in C[] s) pure if (isSomeChar!C) {
bool isPalindrome2(C)(in C[] s) pure if (isSomeChar!C) {
Line 1,651: Line 1,651:
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("salàlas"));
assert(pali("salàlas"));
}</lang>
}</syntaxhighlight>


===Low-level 32-bit Unicode Version===
===Low-level 32-bit Unicode Version===
<lang d>import std.stdio, core.exception, std.traits;
<syntaxhighlight lang="d">import std.stdio, core.exception, std.traits;


// assume alloca() to be pure for this program
// assume alloca() to be pure for this program
Line 1,692: Line 1,692:
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("salàlas"));
assert(pali("salàlas"));
}</lang>
}</syntaxhighlight>


===Low-level ASCII Version===
===Low-level ASCII Version===
<lang d>bool isPalindrome4(in string str) pure nothrow {
<syntaxhighlight lang="d">bool isPalindrome4(in string str) pure nothrow {
if (str.length == 0) return true;
if (str.length == 0) return true;
immutable(char)* s = str.ptr;
immutable(char)* s = str.ptr;
Line 1,717: Line 1,717:
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("ingirumimusnocteetconsumimurigni"));
//assert(pali("salàlas"));
//assert(pali("salàlas"));
}</lang>
}</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==


<lang dartlang>
<syntaxhighlight lang="dartlang">
bool isPalindrome(String s){
bool isPalindrome(String s){
for(int i = 0; i < s.length/2;i++){
for(int i = 0; i < s.length/2;i++){
Line 1,729: Line 1,729:
return true;
return true;
}
}
</syntaxhighlight>
</lang>


=={{header|Delphi}}==
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">uses
<lang Delphi>uses
SysUtils, StrUtils;
SysUtils, StrUtils;


Line 1,738: Line 1,738:
begin
begin
Result := SameText(aSrcString, ReverseString(aSrcString));
Result := SameText(aSrcString, ReverseString(aSrcString));
end;</lang>
end;</syntaxhighlight>


=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang dyalect>func isPalindrom(str) {
<syntaxhighlight lang="dyalect">func isPalindrom(str) {
str == str.Reverse()
str == str.Reverse()
}
}


print(isPalindrom("ingirumimusnocteetconsumimurigni"))</lang>
print(isPalindrom("ingirumimusnocteetconsumimurigni"))</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==


<lang dejavu>palindrome?:
<syntaxhighlight lang="dejavu">palindrome?:
local :seq chars
local :seq chars
local :len-seq -- len seq
local :len-seq -- len seq
Line 1,760: Line 1,760:


!. palindrome? "ingirumimusnocteetconsumimurigni"
!. palindrome? "ingirumimusnocteetconsumimurigni"
!. palindrome? "nope"</lang>
!. palindrome? "nope"</syntaxhighlight>
{{out}}
{{out}}
<pre>true
<pre>true
Line 1,771: Line 1,771:
The for loop syntax is <code>for <var>key pattern</var> => <var>value pattern</var> in <var>collection</var> { ... }</code>, <code>?</code> imposes an additional boolean condition on a pattern (it may be read “''such that''”), and if the pattern does not match in a for loop then the iteration is skipped, so false is returned only if <code>upper[last - i] != c</code>.
The for loop syntax is <code>for <var>key pattern</var> => <var>value pattern</var> in <var>collection</var> { ... }</code>, <code>?</code> imposes an additional boolean condition on a pattern (it may be read “''such that''”), and if the pattern does not match in a for loop then the iteration is skipped, so false is returned only if <code>upper[last - i] != c</code>.


<lang e>def isPalindrome(string :String) {
<syntaxhighlight lang="e">def isPalindrome(string :String) {
def upper := string.toUpperCase()
def upper := string.toUpperCase()
def last := upper.size() - 1
def last := upper.size() - 1
Line 1,778: Line 1,778:
}
}
return true
return true
}</lang>
}</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang lisp>
<syntaxhighlight lang="lisp">
;; returns #t or #f
;; returns #t or #f
(define (palindrome? string)
(define (palindrome? string)
Line 1,790: Line 1,790:
;;(let ((string (string-replace string "/\ /" "" "g")))
;;(let ((string (string-replace string "/\ /" "" "g")))
;;(equal? (string->list string) (reverse (string->list string)))))
;;(equal? (string->list string) (reverse (string->list string)))))
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
is_palindrome (a_string: STRING): BOOLEAN
is_palindrome (a_string: STRING): BOOLEAN
-- Is `a_string' a palindrome?
-- Is `a_string' a palindrome?
Line 1,812: Line 1,812:
end
end
end
end
</syntaxhighlight>
</lang>


=={{header|Ela}}==
=={{header|Ela}}==


<lang ela>open list string
<syntaxhighlight lang="ela">open list string


isPalindrome xs = xs == reverse xs
isPalindrome xs = xs == reverse xs
isPalindrome <| toList "ingirumimusnocteetconsumimurigni"
isPalindrome <| toList "ingirumimusnocteetconsumimurigni"
</syntaxhighlight>
</lang>


Function <code>reverse</code> is taken from list module and is defined as:
Function <code>reverse</code> is taken from list module and is defined as:


<lang ela>reverse = foldl (flip (::)) (nil xs)
<syntaxhighlight lang="ela">reverse = foldl (flip (::)) (nil xs)


foldl f z (x::xs) = foldl f (f z x) xs
foldl f z (x::xs) = foldl f (f z x) xs
foldl _ z [] = z
foldl _ z [] = z
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>
<syntaxhighlight lang="elixir">
defmodule PalindromeDetection do
defmodule PalindromeDetection do
def is_palindrome(str), do: str == String.reverse(str)
def is_palindrome(str), do: str == String.reverse(str)
end
end
</syntaxhighlight>
</lang>
Note: Because of Elixir's strong Unicode support, this even supports graphemes:
Note: Because of Elixir's strong Unicode support, this even supports graphemes:
<pre>
<pre>
Line 1,847: Line 1,847:


=={{header|Elm}}==
=={{header|Elm}}==
<lang elm>import String exposing (reverse, length)
<syntaxhighlight lang="elm">import String exposing (reverse, length)
import Html exposing (Html, Attribute, text, div, input)
import Html exposing (Html, Attribute, text, div, input)
import Html.Attributes exposing (placeholder, value, style)
import Html.Attributes exposing (placeholder, value, style)
Line 1,891: Line 1,891:
, ("font-size", "1em")
, ("font-size", "1em")
, ("text-align", "left")
, ("text-align", "left")
]</lang>
]</syntaxhighlight>


Link to live demo: http://dc25.github.io/palindromeDetectionElm/
Link to live demo: http://dc25.github.io/palindromeDetectionElm/


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang lisp>(defun palindrome (s)
<syntaxhighlight lang="lisp">(defun palindrome (s)
(string= s (reverse s)))</lang>
(string= s (reverse s)))</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( palindrome ).
-module( palindrome ).


Line 1,919: Line 1,919:


display( String1, String2 ) -> io:fwrite( "Is ~p a palindrom? ~p~n", [String1, is_palindrome(String2)] ).
display( String1, String2 ) -> io:fwrite( "Is ~p a palindrom? ~p~n", [String1, is_palindrome(String2)] ).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,929: Line 1,929:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function isPalindrome(sequence s)
<syntaxhighlight lang="euphoria">function isPalindrome(sequence s)
for i = 1 to length(s)/2 do
for i = 1 to length(s)/2 do
if s[i] != s[$-i+1] then
if s[i] != s[$-i+1] then
Line 1,936: Line 1,936:
end for
end for
return 1
return 1
end function</lang>
end function</syntaxhighlight>


<lang euphoria>
<syntaxhighlight lang="euphoria">
include std/sequence.e -- reverse
include std/sequence.e -- reverse
include std/console.e -- display
include std/console.e -- display
Line 1,952: Line 1,952:
s = remove_all(' ',upper(s))
s = remove_all(' ',upper(s))
display(iif(equal(s,reverse(s)),"true","false"))
display(iif(equal(s,reverse(s)),"true","false"))
end procedure</lang>
end procedure</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,968: Line 1,968:


{{Works with| Office 265 Betas 2021}}
{{Works with| Office 265 Betas 2021}}
<lang lisp>ISPALINDROME
<syntaxhighlight lang="lisp">ISPALINDROME
=LAMBDA(s,
=LAMBDA(s,
LET(
LET(
Line 1,978: Line 1,978:
CONCAT(lcs) = CONCAT(REVERSE(lcs))
CONCAT(lcs) = CONCAT(REVERSE(lcs))
)
)
)</lang>
)</syntaxhighlight>


and assuming that the following generic lambdas are also bound to the names CHARS, FILTERP, and REVERSE in the Name Manager for the active WorkBook:
and assuming that the following generic lambdas are also bound to the names CHARS, FILTERP, and REVERSE in the Name Manager for the active WorkBook:


<lang lisp>CHARS
<syntaxhighlight lang="lisp">CHARS
=LAMBDA(s,
=LAMBDA(s,
MID(s, ROW(INDIRECT("1:" & LEN(s))), 1)
MID(s, ROW(INDIRECT("1:" & LEN(s))), 1)
Line 2,005: Line 2,005:
)
)
)
)
)</lang>
)</syntaxhighlight>
{{Out}}
{{Out}}
{| class="wikitable"
{| class="wikitable"
Line 2,046: Line 2,046:


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>let isPalindrome (s: string) =
<syntaxhighlight lang="fsharp">let isPalindrome (s: string) =
let arr = s.ToCharArray()
let arr = s.ToCharArray()
arr = Array.rev arr</lang>
arr = Array.rev arr</syntaxhighlight>


Examples:
Examples:
<lang fsharp>isPalindrome "abcba"
<syntaxhighlight lang="fsharp">isPalindrome "abcba"
val it : bool = true
val it : bool = true
isPalindrome ("In girum imus nocte et consumimur igni".Replace(" ", "").ToLower());;
isPalindrome ("In girum imus nocte et consumimur igni".Replace(" ", "").ToLower());;
val it : bool = true
val it : bool = true
isPalindrome "abcdef"
isPalindrome "abcdef"
val it : bool = false</lang>
val it : bool = false</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: kernel sequences ;
<syntaxhighlight lang="factor">USING: kernel sequences ;
: palindrome? ( str -- ? ) dup reverse = ;</lang>
: palindrome? ( str -- ? ) dup reverse = ;</syntaxhighlight>


=={{header|Falcon}}==
=={{header|Falcon}}==
'''VBA/Python programmer's approach not sure if it's the most falconic way'''
'''VBA/Python programmer's approach not sure if it's the most falconic way'''
<lang falcon>
<syntaxhighlight lang="falcon">
/* created by Aykayayciti Earl Lamont Montgomery
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
April 9th, 2018 */
Line 2,076: Line 2,076:
a = "mom"
a = "mom"
> is_palindrome(a)
> is_palindrome(a)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,084: Line 2,084:


'''more falconic'''
'''more falconic'''
<lang falcon>
<syntaxhighlight lang="falcon">
/* created by Aykayayciti Earl Lamont Montgomery
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
April 9th, 2018 */
Line 2,090: Line 2,090:
b = "mom"
b = "mom"
> strUpper(b).replace(" ", "") == strUpper(b[-1:0]) ? "Is a palindrome" : "Is not a palindrome"
> strUpper(b).replace(" ", "") == strUpper(b[-1:0]) ? "Is a palindrome" : "Is not a palindrome"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,099: Line 2,099:
=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class Palindrome
class Palindrome
{
{
Line 2,120: Line 2,120:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|FBSL}}==
=={{header|FBSL}}==


<lang qbasic>#APPTYPE CONSOLE
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE


FUNCTION stripNonAlpha(BYVAL s AS STRING) AS STRING
FUNCTION stripNonAlpha(BYVAL s AS STRING) AS STRING
Line 2,151: Line 2,151:


PAUSE
PAUSE
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,160: Line 2,160:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: first over c@ ;
<syntaxhighlight lang="forth">: first over c@ ;
: last >r 2dup + 1- c@ r> swap ;
: last >r 2dup + 1- c@ r> swap ;
: palindrome? ( c-addr u -- f )
: palindrome? ( c-addr u -- f )
Line 2,168: Line 2,168:
1 /string 1-
1 /string 1-
again ;
again ;
</syntaxhighlight>
</lang>


FIRST and LAST are once-off words that could be beheaded immediately afterwards.
FIRST and LAST are once-off words that could be beheaded immediately afterwards.
Line 2,178: Line 2,178:
'''Below is a separate Forth program that detects palindrome phrases as well as single word palindromes. It was programmed using gforth.'''
'''Below is a separate Forth program that detects palindrome phrases as well as single word palindromes. It was programmed using gforth.'''


<lang forth>
<syntaxhighlight lang="forth">
variable temp-addr
variable temp-addr


Line 2,210: Line 2,210:
else ." << Not >> a Palindrome."
else ." << Not >> a Palindrome."
then cr ;
then cr ;
</syntaxhighlight>
</lang>


Example:
Example:
Line 2,221: Line 2,221:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>program palindro
<syntaxhighlight lang="fortran">program palindro


implicit none
implicit none
Line 2,234: Line 2,234:
print *, is_palindro("last test")
print *, is_palindro("last test")


contains</lang>
contains</syntaxhighlight>


'''Non-recursive'''
'''Non-recursive'''


<lang fortran>! non-recursive
<syntaxhighlight lang="fortran">! non-recursive
function is_palindro(t)
function is_palindro(t)
logical :: is_palindro
logical :: is_palindro
Line 2,263: Line 2,263:
forall(i=1:len(t)) s(len(t)-i+1:len(t)-i+1) = t(i:i)
forall(i=1:len(t)) s(len(t)-i+1:len(t)-i+1) = t(i:i)
isp = ( s == t )
isp = ( s == t )
end function is_palindro2</lang>
end function is_palindro2</syntaxhighlight>


'''Recursive'''
'''Recursive'''
<lang fortran> recursive function is_palindro_r (t) result (isp)
<syntaxhighlight lang="fortran"> recursive function is_palindro_r (t) result (isp)


implicit none
implicit none
Line 2,274: Line 2,274:
isp = len (t) == 0 .or. t (: 1) == t (len (t) :) .and. is_palindro_r (t (2 : len (t) - 1))
isp = len (t) == 0 .or. t (: 1) == t (len (t) :) .and. is_palindro_r (t (2 : len (t) - 1))


end function is_palindro_r</lang>
end function is_palindro_r</syntaxhighlight>


<lang fortran>end program palindro</lang>
<syntaxhighlight lang="fortran">end program palindro</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang FreeBASIC>' version 20-06-2015
<syntaxhighlight lang="freebasic">' version 20-06-2015
' compile with: fbc -s console "filename".bas
' compile with: fbc -s console "filename".bas


Line 2,354: Line 2,354:
Print : Print : Print "Hit any key to end program"
Print : Print : Print "Hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre> reverse(test) = FALSE
<pre> reverse(test) = FALSE
Line 2,366: Line 2,366:
For example, the string "og\u0308o" represents an o, a g with combining diaeresis, followed by the letter o. Or, in other words, "og̈o". Note that while there are four Unicode codepoints, only three "graphemes" are displayed. Using Frink's smart "reverse" function preserves these combined graphemes and detects them correctly as palindromes.
For example, the string "og\u0308o" represents an o, a g with combining diaeresis, followed by the letter o. Or, in other words, "og̈o". Note that while there are four Unicode codepoints, only three "graphemes" are displayed. Using Frink's smart "reverse" function preserves these combined graphemes and detects them correctly as palindromes.


<lang frink>isPalindrome[x] := x == reverse[x]
<syntaxhighlight lang="frink">isPalindrome[x] := x == reverse[x]
</syntaxhighlight>
</lang>


Test in Frink with upper-plane Unicode:
Test in Frink with upper-plane Unicode:
<lang frink>isPalindrome["x\u{1f638}x"]</lang>
<syntaxhighlight lang="frink">isPalindrome["x\u{1f638}x"]</syntaxhighlight>


<code>
<code>
Line 2,385: Line 2,385:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>ZapGremlins := function(s)
<syntaxhighlight lang="gap">ZapGremlins := function(s)
local upper, lower, c, i, n, t;
local upper, lower, c, i, n, t;
upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Line 2,411: Line 2,411:
t := ZapGremlins(s);
t := ZapGremlins(s);
return t = Reversed(t);
return t = Reversed(t);
end;</lang>
end;</syntaxhighlight>


=={{header|GML}}==
=={{header|GML}}==
<syntaxhighlight lang="go">
<lang go>
//Setting a var from an argument passed to the script
//Setting a var from an argument passed to the script
var str;
var str;
Line 2,430: Line 2,430:
//returns true if the sequence is a palindrome else returns false
//returns true if the sequence is a palindrome else returns false
return (str == inv);
return (str == inv);
</syntaxhighlight>
</lang>


Palindrome detection using a [http://rosettacode.org/wiki/Loop/Downward_For#GML Downward For-Loop]
Palindrome detection using a [http://rosettacode.org/wiki/Loop/Downward_For#GML Downward For-Loop]


<syntaxhighlight lang="go">
<lang go>


//Remove everything except for letters and digits and convert the string to lowercase. source is what will be compared to str.
//Remove everything except for letters and digits and convert the string to lowercase. source is what will be compared to str.
Line 2,446: Line 2,446:
//Return if it is a palindrome.
//Return if it is a palindrome.
return source == str;
return source == str;
</syntaxhighlight>
</lang>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package pal
<syntaxhighlight lang="go">package pal


func IsPal(s string) bool {
func IsPal(s string) bool {
Line 2,460: Line 2,460:
}
}
return true
return true
}</lang>
}</syntaxhighlight>


This version works with Unicode,
This version works with Unicode,


<syntaxhighlight lang="go">
<lang go>
func isPalindrome(s string) bool {
func isPalindrome(s string) bool {
runes := []rune(s)
runes := []rune(s)
Line 2,474: Line 2,474:
}
}
return true
return true
}</lang>
}</syntaxhighlight>


Or using more slicing,
Or using more slicing,


<syntaxhighlight lang="go">
<lang go>
func isPalindrome(s string) bool {
func isPalindrome(s string) bool {
runes := []rune(s)
runes := []rune(s)
Line 2,488: Line 2,488:
}
}
return true
return true
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Line 2,494: Line 2,494:


Solution:
Solution:
<lang groovy>def isPalindrome = { String s ->
<syntaxhighlight lang="groovy">def isPalindrome = { String s ->
s == s?.reverse()
s == s?.reverse()
}</lang>
}</syntaxhighlight>


Test program:
Test program:
<lang groovy>println isPalindrome("")
<syntaxhighlight lang="groovy">println isPalindrome("")
println isPalindrome("a")
println isPalindrome("a")
println isPalindrome("abcdefgfedcba")
println isPalindrome("abcdefgfedcba")
println isPalindrome("abcdeffedcba")
println isPalindrome("abcdeffedcba")
println isPalindrome("abcedfgfedcb")</lang>
println isPalindrome("abcedfgfedcb")</syntaxhighlight>


{{out}}
{{out}}
Line 2,517: Line 2,517:


Solution:
Solution:
<lang groovy>def isPalindrome = { String s ->
<syntaxhighlight lang="groovy">def isPalindrome = { String s ->
def n = s.size()
def n = s.size()
n < 2 || s[0..<n/2] == s[-1..(-n/2)]
n < 2 || s[0..<n/2] == s[-1..(-n/2)]
}</lang>
}</syntaxhighlight>


Test program and output are the same.
Test program and output are the same.
Line 2,528: Line 2,528:


Solution follows the [[#C|C palindrome_r]] recursive solution:
Solution follows the [[#C|C palindrome_r]] recursive solution:
<lang groovy>def isPalindrome
<syntaxhighlight lang="groovy">def isPalindrome
isPalindrome = { String s ->
isPalindrome = { String s ->
def n = s.size()
def n = s.size()
n < 2 || (s[0] == s[n-1] && isPalindrome(s[1..<(n-1)]))
n < 2 || (s[0] == s[n-1] && isPalindrome(s[1..<(n-1)]))
}</lang>
}</syntaxhighlight>


Test program and output are the same.
Test program and output are the same.
Line 2,543: Line 2,543:
A string is a palindrome if reversing it we obtain the same string.
A string is a palindrome if reversing it we obtain the same string.


<lang haskell>is_palindrome x = x == reverse x</lang>
<syntaxhighlight lang="haskell">is_palindrome x = x == reverse x</syntaxhighlight>


Or, applicative and point-free, with some pre-processing of data (shedding white space and upper case):
Or, applicative and point-free, with some pre-processing of data (shedding white space and upper case):


<lang haskell>import Data.Bifunctor (second)
<syntaxhighlight lang="haskell">import Data.Bifunctor (second)
import Data.Char (toLower)
import Data.Char (toLower)


Line 2,582: Line 2,582:
prepared cs = [toLower c | c <- cs, ' ' /= c]
prepared cs = [toLower c | c <- cs, ' ' /= c]


showResult f s = (show s) <> " -> " <> show (f s)</lang>
showResult f s = (show s) <> " -> " <> show (f s)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>"" -> True
<pre>"" -> True
Line 2,606: Line 2,606:
of the remaining list here).
of the remaining list here).


<lang haskell>is_palindrome_r x | length x <= 1 = True
<syntaxhighlight lang="haskell">is_palindrome_r x | length x <= 1 = True
| head x == last x = is_palindrome_r . tail. init $ x
| head x == last x = is_palindrome_r . tail. init $ x
| otherwise = False</lang>
| otherwise = False</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
{{incorrect|HicEst|The stripping of spaces and case conversion should be outside the palindrome detection.}}
{{incorrect|HicEst|The stripping of spaces and case conversion should be outside the palindrome detection.}}


<lang hicest> result = Palindrome( "In girum imus nocte et consumimur igni" ) ! returns 1
<syntaxhighlight lang="hicest"> result = Palindrome( "In girum imus nocte et consumimur igni" ) ! returns 1
END
END


Line 2,629: Line 2,629:
IF( Palindrome == 0 ) RETURN
IF( Palindrome == 0 ) RETURN
ENDDO
ENDDO
END</lang>
END</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main(arglist)
<syntaxhighlight lang="icon">procedure main(arglist)
every writes(s := !arglist) do write( if palindrome(s) then " is " else " is not", " a palindrome.")
every writes(s := !arglist) do write( if palindrome(s) then " is " else " is not", " a palindrome.")
end</lang>
end</syntaxhighlight>


The following simple procedure uses the built-in reverse. Reverse creates a transient string which will get garbage collected.
The following simple procedure uses the built-in reverse. Reverse creates a transient string which will get garbage collected.
<lang Icon>procedure palindrome(s) #: return s if s is a palindrome
<syntaxhighlight lang="icon">procedure palindrome(s) #: return s if s is a palindrome
return s == reverse(s)
return s == reverse(s)
end</lang>
end</syntaxhighlight>
{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}


Line 2,645: Line 2,645:


This version uses positive and negative sub-scripting and works not only on strings but lists of strings, such as ["ab","ab"] or ["ab","x"] the first list would pass the test but the second wouldn't.
This version uses positive and negative sub-scripting and works not only on strings but lists of strings, such as ["ab","ab"] or ["ab","x"] the first list would pass the test but the second wouldn't.
<lang Icon>procedure palindrome(x) #: return x if s is x palindrome
<syntaxhighlight lang="icon">procedure palindrome(x) #: return x if s is x palindrome
local i
local i
every if x[i := 1 to (*x+ 1)/2] ~== x[-i] then fail
every if x[i := 1 to (*x+ 1)/2] ~== x[-i] then fail
return x
return x
end</lang>
end</syntaxhighlight>


=={{header|Ioke}}==
=={{header|Ioke}}==
<lang ioke>Text isPalindrome? = method(self chars == self chars reverse)</lang>
<syntaxhighlight lang="ioke">Text isPalindrome? = method(self chars == self chars reverse)</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 2,658: Line 2,658:


Reverse and match method
Reverse and match method
<lang j>isPalin0=: -: |.</lang>
<syntaxhighlight lang="j">isPalin0=: -: |.</syntaxhighlight>
Example usage
Example usage
<lang j> isPalin0 'ABBA'
<syntaxhighlight lang="j"> isPalin0 'ABBA'
1
1
isPalin0 -.&' ' tolower 'In girum imus nocte et consumimur igni'
isPalin0 -.&' ' tolower 'In girum imus nocte et consumimur igni'
1</lang>
1</syntaxhighlight>


'''Recursive'''
'''Recursive'''


Tacit and explicit verbs:
Tacit and explicit verbs:
<lang j>isPalin1=: 0:`($:@(}.@}:))@.({.={:)`1:@.(1>:#)
<syntaxhighlight lang="j">isPalin1=: 0:`($:@(}.@}:))@.({.={:)`1:@.(1>:#)


isPalin2=: monad define
isPalin2=: monad define
if. 1>:#y do. 1 return. end.
if. 1>:#y do. 1 return. end.
if. ({.={:)y do. isPalin2 }.}:y else. 0 end.
if. ({.={:)y do. isPalin2 }.}:y else. 0 end.
)</lang>
)</syntaxhighlight>


Note that while these recursive verbs are bulkier and more complicated, they are also several thousand times more inefficient than isPalin0.
Note that while these recursive verbs are bulkier and more complicated, they are also several thousand times more inefficient than isPalin0.


<lang j> foo=: foo,|.foo=:2000$a.
<syntaxhighlight lang="j"> foo=: foo,|.foo=:2000$a.
ts=:6!:2,7!:2 NB. time and space required to execute sentence
ts=:6!:2,7!:2 NB. time and space required to execute sentence
ts 'isPalin0 foo'
ts 'isPalin0 foo'
Line 2,688: Line 2,688:
1599.09 1164.23
1599.09 1164.23
'isPalin2 foo' %&ts 'isPalin0 foo'
'isPalin2 foo' %&ts 'isPalin0 foo'
3967.53 2627.04</lang>
3967.53 2627.04</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Line 2,694: Line 2,694:
'''Non-Recursive'''
'''Non-Recursive'''


<lang java>public static boolean pali(String testMe){
<syntaxhighlight lang="java">public static boolean pali(String testMe){
StringBuilder sb = new StringBuilder(testMe);
StringBuilder sb = new StringBuilder(testMe);
return testMe.equals(sb.reverse().toString());
return testMe.equals(sb.reverse().toString());
}</lang>
}</syntaxhighlight>


'''Non-Recursive using indexes (supports upper-plane Unicode)'''
'''Non-Recursive using indexes (supports upper-plane Unicode)'''
<lang java>public static boolean isPalindrome(String input) {
<syntaxhighlight lang="java">public static boolean isPalindrome(String input) {
for (int i = 0, j = input.length() - 1; i < j; i++, j--) {
for (int i = 0, j = input.length() - 1; i < j; i++, j--) {
char startChar = input.charAt(i);
char startChar = input.charAt(i);
Line 2,718: Line 2,718:
}
}
return true;
return true;
}</lang>
}</syntaxhighlight>


'''Recursive (this version does not work correctly with upper-plane Unicode)'''
'''Recursive (this version does not work correctly with upper-plane Unicode)'''


<lang java>public static boolean rPali(String testMe){
<syntaxhighlight lang="java">public static boolean rPali(String testMe){
if(testMe.length()<=1){
if(testMe.length()<=1){
return true;
return true;
Line 2,730: Line 2,730:
}
}
return rPali(testMe.substring(1, testMe.length()-1));
return rPali(testMe.substring(1, testMe.length()-1));
}</lang>
}</syntaxhighlight>


'''Recursive using indexes (this version does not work correctly with upper-plane Unicode)'''
'''Recursive using indexes (this version does not work correctly with upper-plane Unicode)'''


<lang java>public static boolean rPali(String testMe){
<syntaxhighlight lang="java">public static boolean rPali(String testMe){
int strLen = testMe.length();
int strLen = testMe.length();
return rPaliHelp(testMe, strLen-1, strLen/2, 0);
return rPaliHelp(testMe, strLen-1, strLen/2, 0);
Line 2,748: Line 2,748:
return rPaliHelp(testMe, strLen, testLen, index + 1);
return rPaliHelp(testMe, strLen, testLen, index + 1);
}
}
</syntaxhighlight>
</lang>


'''Regular Expression'''
'''Regular Expression'''
([http://stackoverflow.com/questions/3664881/how-does-this-java-regex-detect-palindromes source])
([http://stackoverflow.com/questions/3664881/how-does-this-java-regex-detect-palindromes source])
<lang java>public static boolean pali(String testMe){
<syntaxhighlight lang="java">public static boolean pali(String testMe){
return testMe.matches("|(?:(.)(?<=(?=^.*?(\\1\\2?)$).*))+(?<=(?=^\\2$).*)");
return testMe.matches("|(?:(.)(?<=(?=^.*?(\\1\\2?)$).*))+(?<=(?=^\\2$).*)");
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>function isPalindrome(str) {
<syntaxhighlight lang="javascript">function isPalindrome(str) {
return str === str.split("").reverse().join("");
return str === str.split("").reverse().join("");
}
}


console.log(isPalindrome("ingirumimusnocteetconsumimurigni"));</lang>
console.log(isPalindrome("ingirumimusnocteetconsumimurigni"));</syntaxhighlight>




ES6 implementation
ES6 implementation
<lang javascript>var isPal = str => str === str.split("").reverse().join("");</lang>
<syntaxhighlight lang="javascript">var isPal = str => str === str.split("").reverse().join("");</syntaxhighlight>


Or, ignoring spaces and variations in case:
Or, ignoring spaces and variations in case:


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {


// isPalindrome :: String -> Bool
// isPalindrome :: String -> Bool
Line 2,801: Line 2,801:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>true</pre>
<pre>true</pre>


=={{header|jq}}==
=={{header|jq}}==
<lang jq>def palindrome: explode as $in | ($in|reverse) == $in;</lang>
<syntaxhighlight lang="jq">def palindrome: explode as $in | ($in|reverse) == $in;</syntaxhighlight>
'''Example''':
'''Example''':
"salàlas" | palindrome
"salàlas" | palindrome
Line 2,813: Line 2,813:


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>/* Palindrome detection, in Jsish */
<syntaxhighlight lang="javascript">/* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
if (!exact) {
Line 2,840: Line 2,840:
isPalindrome('Never odd or even', false) ==> true
isPalindrome('Never odd or even', false) ==> true
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


Most of that code is for testing, using echo mode lines (semicolon in column 1)
Most of that code is for testing, using echo mode lines (semicolon in column 1)
Line 2,858: Line 2,858:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>palindrome(s) = s == reverse(s)</lang>
<syntaxhighlight lang="julia">palindrome(s) = s == reverse(s)</syntaxhighlight>
<b> Non-Recursive </b>
<b> Non-Recursive </b>
<lang julia>
<syntaxhighlight lang="julia">
function palindrome(s)
function palindrome(s)
len = length(s)
len = length(s)
Line 2,870: Line 2,870:
return true
return true
end
end
</syntaxhighlight>
</lang>
<b> Recursive </b>
<b> Recursive </b>
<lang julia>
<syntaxhighlight lang="julia">
function palindrome(s)
function palindrome(s)
len = length(s)
len = length(s)
Line 2,882: Line 2,882:
end
end
return false
return false
end</lang>
end</syntaxhighlight>


=={{header|k}}==
=={{header|k}}==
<lang k>is_palindrome:{x~|x}</lang>
<syntaxhighlight lang="k">is_palindrome:{x~|x}</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


/* These functions deal automatically with Unicode as all strings are UTF-16 encoded in Kotlin */
/* These functions deal automatically with Unicode as all strings are UTF-16 encoded in Kotlin */
Line 2,916: Line 2,916:
println("'$candidate' is ${if (isInexactPalindrome(candidate)) "an" else "not an"} inexact palindrome")
println("'$candidate' is ${if (isInexactPalindrome(candidate)) "an" else "not an"} inexact palindrome")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,935: Line 2,935:


=={{header|langur}}==
=={{header|langur}}==
<lang langur>val .ispal = f len(.s) > 0 and .s == s2s .s, len(.s)..1
<syntaxhighlight lang="langur">val .ispal = f len(.s) > 0 and .s == s2s .s, len(.s)..1


val .tests = h{
val .tests = h{
Line 2,957: Line 2,957:
val .foundpal = .ispal(.word)
val .foundpal = .ispal(.word)
writeln .word, ": ", .foundpal, if(.foundpal == .tests[.word]: ""; " (FAILED TEST)")
writeln .word, ": ", .foundpal, if(.foundpal == .tests[.word]: ""; " (FAILED TEST)")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,976: Line 2,976:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define ispalindrome(text::string) => {
<syntaxhighlight lang="lasso">define ispalindrome(text::string) => {


local(_text = string(#text)) // need to make copy to get rid of reference issues
local(_text = string(#text)) // need to make copy to get rid of reference issues
Line 2,991: Line 2,991:
ispalindrome('Hello World')
ispalindrome('Hello World')


ispalindrome('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal – Panama!')</lang>
ispalindrome('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal – Panama!')</syntaxhighlight>
{{out}}
{{out}}
<pre>true
<pre>true
Line 2,998: Line 2,998:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>print isPalindrome("In girum imus nocte et consumimur igni")
<syntaxhighlight lang="lb">print isPalindrome("In girum imus nocte et consumimur igni")
print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "S"))
print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "S"))
print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "SC"))
print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "SC"))
Line 3,019: Line 3,019:
next i
next i
removePunctuation$ = string$
removePunctuation$ = string$
end function</lang>
end function</syntaxhighlight>


{{out}}
{{out}}
Line 3,029: Line 3,029:


=={{header|LiveCode}}==
=={{header|LiveCode}}==
This implementation defaults to exact match, but has an optional parameter to do inexact.<lang LiveCode>function palindrome txt exact
This implementation defaults to exact match, but has an optional parameter to do inexact.<syntaxhighlight lang="livecode">function palindrome txt exact
if exact is empty or exact is not false then
if exact is empty or exact is not false then
set caseSensitive to true --default is false
set caseSensitive to true --default is false
Line 3,044: Line 3,044:
end repeat
end repeat
return revstr
return revstr
end reverse</lang>
end reverse</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to palindrome? :w
<syntaxhighlight lang="logo">to palindrome? :w
output equal? :w reverse :w
output equal? :w reverse :w
end</lang>
end</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function ispalindrome(s) return s == string.reverse(s) end</lang>
<syntaxhighlight lang="lua">function ispalindrome(s) return s == string.reverse(s) end</syntaxhighlight>


=={{header|M4}}==
=={{header|M4}}==
Line 3,058: Line 3,058:
'''Non-recursive'''
'''Non-recursive'''
This uses the <code>invert</code> from [[Reversing a string]].
This uses the <code>invert</code> from [[Reversing a string]].
<lang m4>define(`palindrorev',`ifelse(`$1',invert(`$1'),`yes',`no')')dnl
<syntaxhighlight lang="m4">define(`palindrorev',`ifelse(`$1',invert(`$1'),`yes',`no')')dnl
palindrorev(`ingirumimusnocteetconsumimurigni')
palindrorev(`ingirumimusnocteetconsumimurigni')
palindrorev(`this is not palindrome')</lang>
palindrorev(`this is not palindrome')</syntaxhighlight>


'''Recursive'''
'''Recursive'''
<lang m4>define(`striptwo',`substr(`$1',1,eval(len(`$1')-2))')dnl
<syntaxhighlight lang="m4">define(`striptwo',`substr(`$1',1,eval(len(`$1')-2))')dnl
define(`cmplast',`ifelse(`striptwo(`$1')',,`yes',dnl
define(`cmplast',`ifelse(`striptwo(`$1')',,`yes',dnl
substr(`$1',0,1),substr(`$1',eval(len(`$1')-1),1),`yes',`no')')dnl
substr(`$1',0,1),substr(`$1',eval(len(`$1')-1),1),`yes',`no')')dnl
Line 3,069: Line 3,069:
ifelse(eval(len(`$1')<1),1,`yes',cmplast(`$1'),`yes',`palindro(striptwo(`$1'))',`no')')dnl
ifelse(eval(len(`$1')<1),1,`yes',cmplast(`$1'),`yes',`palindro(striptwo(`$1'))',`no')')dnl
palindro(`ingirumimusnocteetconsumimurigni')
palindro(`ingirumimusnocteetconsumimurigni')
palindro(`this is not palindrome')</lang>
palindro(`this is not palindrome')</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
Line 3,075: Line 3,075:
This uses functions from Maple's built-in <code>StringTools</code> package.
This uses functions from Maple's built-in <code>StringTools</code> package.


<syntaxhighlight lang="maple">
<lang Maple>
with(StringTools):
with(StringTools):


Line 3,083: Line 3,083:


IsPalindrome(LowerCase(DeleteSpace("In girum imus nocte et consumimur igni")));
IsPalindrome(LowerCase(DeleteSpace("In girum imus nocte et consumimur igni")));
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,096: Line 3,096:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Built-in function handling lists, numbers, and strings:
Built-in function handling lists, numbers, and strings:
<lang Mathematica>PalindromeQ</lang>
<syntaxhighlight lang="mathematica">PalindromeQ</syntaxhighlight>
{{out|Examples}}
{{out|Examples}}
<pre>PalindromeQ["TNT"]
<pre>PalindromeQ["TNT"]
Line 3,111: Line 3,111:


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang MATLAB>function trueFalse = isPalindrome(string)
<syntaxhighlight lang="matlab">function trueFalse = isPalindrome(string)
trueFalse = all(string == fliplr(string)); %See if flipping the string produces the original string
trueFalse = all(string == fliplr(string)); %See if flipping the string produces the original string
Line 3,125: Line 3,125:
end
end
end</lang>
end</syntaxhighlight>


{{out|Sample Usage}}
{{out|Sample Usage}}
<lang MATLAB>>> isPalindrome('In girum imus nocte et consumimur igni')
<syntaxhighlight lang="matlab">>> isPalindrome('In girum imus nocte et consumimur igni')


ans =
ans =


1
1
</syntaxhighlight>
</lang>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>palindromep(s) := block([t], t: sremove(" ", sdowncase(s)), sequal(t, sreverse(t)))$
<syntaxhighlight lang="maxima">palindromep(s) := block([t], t: sremove(" ", sdowncase(s)), sequal(t, sreverse(t)))$


palindromep("Sator arepo tenet opera rotas"); /* true */</lang>
palindromep("Sator arepo tenet opera rotas"); /* true */</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
Line 3,144: Line 3,144:
'''Non-recursive'''
'''Non-recursive'''


<lang maxscript>fn isPalindrome s =
<syntaxhighlight lang="maxscript">fn isPalindrome s =
(
(
local reversed = ""
local reversed = ""
for i in s.count to 1 by -1 do reversed += s[i]
for i in s.count to 1 by -1 do reversed += s[i]
return reversed == s
return reversed == s
)</lang>
)</syntaxhighlight>


'''Recursive'''
'''Recursive'''


<lang maxscript>fn isPalindrome_r s =
<syntaxhighlight lang="maxscript">fn isPalindrome_r s =
(
(
if s.count <= 1 then
if s.count <= 1 then
Line 3,167: Line 3,167:
isPalindrome_r (substring s 2 (s.count-2))
isPalindrome_r (substring s 2 (s.count-2))
)
)
)</lang>
)</syntaxhighlight>


'''Testing'''
'''Testing'''


<lang maxscript>local p = "ingirumimusnocteetconsumimurigni"
<syntaxhighlight lang="maxscript">local p = "ingirumimusnocteetconsumimurigni"
format ("'%' is a palindrome? %\n") p (isPalindrome p)
format ("'%' is a palindrome? %\n") p (isPalindrome p)
format ("'%' is a palindrome? %\n") p (isPalindrome_r p)</lang>
format ("'%' is a palindrome? %\n") p (isPalindrome_r p)</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(dup reverse ==) :palindrome?
<syntaxhighlight lang="min">(dup reverse ==) :palindrome?
(dup "" split reverse "" join ==) :str-palindrome?
(dup "" split reverse "" join ==) :str-palindrome?


Line 3,183: Line 3,183:
"racecar" str-palindrome? puts
"racecar" str-palindrome? puts
(a b c) palindrome? puts
(a b c) palindrome? puts
(a b b a) palindrome? puts</lang>
(a b b a) palindrome? puts</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,193: Line 3,193:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>isPalindrome = function(s)
<syntaxhighlight lang="miniscript">isPalindrome = function(s)
// convert to lowercase, and strip non-letters
// convert to lowercase, and strip non-letters
stripped = ""
stripped = ""
Line 3,212: Line 3,212:
if not isPalindrome(testStr) then answer.push "NOT"
if not isPalindrome(testStr) then answer.push "NOT"
answer.push "a palindrome"
answer.push "a palindrome"
print answer.join</lang>
print answer.join</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,219: Line 3,219:


=={{header|Mirah}}==
=={{header|Mirah}}==
<lang mirah>def reverse(s:string)
<syntaxhighlight lang="mirah">def reverse(s:string)
StringBuilder.new(s).reverse.toString()
StringBuilder.new(s).reverse.toString()
end
end
Line 3,230: Line 3,230:
puts palindrome?("Erik") # ==> false
puts palindrome?("Erik") # ==> false
puts palindrome?("palindroom-moordnilap") # ==> true
puts palindrome?("palindroom-moordnilap") # ==> true
puts nil # ==> null</lang>
puts nil # ==> null</syntaxhighlight>


=={{header|ML}}==
=={{header|ML}}==
==={{header|mLite}}===
==={{header|mLite}}===
<lang ocaml>fun to_locase s = implode ` map (c_downcase) ` explode s
<syntaxhighlight lang="ocaml">fun to_locase s = implode ` map (c_downcase) ` explode s


fun only_alpha s = implode ` filter (fn x = c_alphabetic x) ` explode s
fun only_alpha s = implode ` filter (fn x = c_alphabetic x) ` explode s
Line 3,264: Line 3,264:
println ` test (is_palin, "Lagerregal", true, "is a palindrome", "is NOT a palindrome");
println ` test (is_palin, "Lagerregal", true, "is a palindrome", "is NOT a palindrome");
println ` test (is_palin, "Ein Neger mit Gazelle zagt im Regen nie.", true, "is a palindrome", "is NOT a palindrome");
println ` test (is_palin, "Ein Neger mit Gazelle zagt im Regen nie.", true, "is a palindrome", "is NOT a palindrome");
println ` test (is_palin, "something wrong", true, "is a palindrome", "is NOT a palindrome");</lang>
println ` test (is_palin, "something wrong", true, "is a palindrome", "is NOT a palindrome");</syntaxhighlight>
Output:
Output:
<pre>'In girum imus nocte, et consumimur igni' is a palindrome
<pre>'In girum imus nocte, et consumimur igni' is a palindrome
Line 3,276: Line 3,276:


==={{header|Standard ML}}===
==={{header|Standard ML}}===
<lang sml>
<syntaxhighlight lang="sml">
fun palindrome s =
fun palindrome s =
let val cs = explode s in
let val cs = explode s in
cs = rev cs
cs = rev cs
end
end
</syntaxhighlight>
</lang>


=={{header|MMIX}}==
=={{header|MMIX}}==
<lang mmix>argc IS $0
<syntaxhighlight lang="mmix">argc IS $0
argv IS $1
argv IS $1


Line 3,351: Line 3,351:
1H TRAP 0,Fputs,StdOut % print
1H TRAP 0,Fputs,StdOut % print
3H XOR $255,$255,$255
3H XOR $255,$255,$255
TRAP 0,Halt,0 % exit(0)</lang>
TRAP 0,Halt,0 % exit(0)</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE Palindrome;
<syntaxhighlight lang="modula2">MODULE Palindrome;
FROM FormatString IMPORT FormatString;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
FROM Terminal IMPORT WriteString,ReadChar;
Line 3,392: Line 3,392:


ReadChar
ReadChar
END Palindrome.</lang>
END Palindrome.</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE Palindrome;
<syntaxhighlight lang="modula3">MODULE Palindrome;


IMPORT Text;
IMPORT Text;
Line 3,409: Line 3,409:
RETURN TRUE;
RETURN TRUE;
END isPalindrome;
END isPalindrome;
END Palindrome.</lang>
END Palindrome.</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>def is_palindrome(s)
<syntaxhighlight lang="nanoquery">def is_palindrome(s)
temp = ""
temp = ""
for char in s
for char in s
Line 3,421: Line 3,421:


return list(temp) = list(temp).reverse()
return list(temp) = list(temp).reverse()
end</lang>
end</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;
using Nemerle.Utility.NString; //contains methods Explode() and Implode() which convert string -> list[char] and back
using Nemerle.Utility.NString; //contains methods Explode() and Implode() which convert string -> list[char] and back
Line 3,439: Line 3,439:
WriteLine("radar is a palindrome: {0}", IsPalindrome("radar"));
WriteLine("radar is a palindrome: {0}", IsPalindrome("radar"));
}
}
}</lang>
}</syntaxhighlight>
And a function to remove spaces and punctuation and convert to lowercase
And a function to remove spaces and punctuation and convert to lowercase
<lang Nemerle>Clean( text : string ) : string
<syntaxhighlight lang="nemerle">Clean( text : string ) : string
{
{
def sepchars = Explode(",.;:-?!()' ");
def sepchars = Explode(",.;:-?!()' ");
Concat( "", Split(text, sepchars)).ToLower()
Concat( "", Split(text, sepchars)).ToLower()
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{Trans|REXX}}
{{Trans|REXX}}
<lang netrexx>
<syntaxhighlight lang="netrexx">
y='In girum imus nocte et consumimur igni'
y='In girum imus nocte et consumimur igni'


Line 3,467: Line 3,467:
/* and translate to uppercase. */
/* and translate to uppercase. */
return x==x.reverse() /* returns 1 if exactly equal */
return x==x.reverse() /* returns 1 if exactly equal */
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
Works likewise for strings and for lists
Works likewise for strings and for lists
<lang lisp>
<syntaxhighlight lang="lisp">
(define (palindrome? s)
(define (palindrome? s)
(setq r s)
(setq r s)
Line 3,480: Line 3,480:
(define (palindrome? s)
(define (palindrome? s)
(= s (reverse (copy s))))
(= s (reverse (copy s))))
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
The following program detects if UTF-8 strings are exact palindromes. If "exact" is set to "false", it ignores the white spaces and the differences of letter case to detect inexact palindromes. Differences in punctuation are still relevant.
The following program detects if UTF-8 strings are exact palindromes. If "exact" is set to "false", it ignores the white spaces and the differences of letter case to detect inexact palindromes. Differences in punctuation are still relevant.
<lang nim>import unicode
<syntaxhighlight lang="nim">import unicode




Line 3,527: Line 3,527:
check "In girum imus nocte et consumimur igni"
check "In girum imus nocte et consumimur igni"
check "Esope reste ici et se repose"
check "Esope reste ici et se repose"
check "This is a palindrom"</lang>
check "This is a palindrom"</syntaxhighlight>


{{out}}
{{out}}
Line 3,539: Line 3,539:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
bundle Default {
bundle Default {
class Test {
class Test {
Line 3,560: Line 3,560:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>let is_palindrome s =
<syntaxhighlight lang="ocaml">let is_palindrome s =
let l = String.length s in
let l = String.length s in
let rec comp n =
let rec comp n =
n = 0 || (s.[l-n] = s.[n-1] && comp (n-1)) in
n = 0 || (s.[l-n] = s.[n-1] && comp (n-1)) in
comp (l / 2)</lang>
comp (l / 2)</syntaxhighlight>


and here a function to remove the white spaces in the string:
and here a function to remove the white spaces in the string:


<lang ocaml>let rem_space str =
<syntaxhighlight lang="ocaml">let rem_space str =
let len = String.length str in
let len = String.length str in
let res = Bytes.create len in
let res = Bytes.create len in
Line 3,586: Line 3,586:
in
in
aux 0 0
aux 0 0
</syntaxhighlight>
</lang>


and to make the test case insensitive, just use the function <tt>String.lowercase_ascii</tt>.
and to make the test case insensitive, just use the function <tt>String.lowercase_ascii</tt>.
Line 3,592: Line 3,592:
=={{header|Octave}}==
=={{header|Octave}}==
'''Recursive'''
'''Recursive'''
<lang octave>function v = palindro_r(s)
<syntaxhighlight lang="octave">function v = palindro_r(s)
if ( length(s) == 1 )
if ( length(s) == 1 )
v = true;
v = true;
Line 3,605: Line 3,605:
v = false;
v = false;
endif
endif
endfunction</lang>
endfunction</syntaxhighlight>


'''Non-recursive'''
'''Non-recursive'''
<lang octave>function v = palindro(s)
<syntaxhighlight lang="octave">function v = palindro(s)
v = all( (s == s(length(s):-1:1)) == 1);
v = all( (s == s(length(s):-1:1)) == 1);
endfunction</lang>
endfunction</syntaxhighlight>


'''Testing'''
'''Testing'''
<lang octave>palindro_r("ingirumimusnocteetconsumimurigni")
<syntaxhighlight lang="octave">palindro_r("ingirumimusnocteetconsumimurigni")
palindro("satorarepotenetoperarotas")</lang>
palindro("satorarepotenetoperarotas")</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>String method: isPalindrome self reverse self == ;</lang>
<syntaxhighlight lang="oforth">String method: isPalindrome self reverse self == ;</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
; simple case - only lowercase letters
; simple case - only lowercase letters
(define (palindrome? str)
(define (palindrome? str)
Line 3,649: Line 3,649:
(print (palindrome? "This is not a palindrome"))
(print (palindrome? "This is not a palindrome"))
; ==> #false
; ==> #false
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>fun {IsPalindrome S}
<syntaxhighlight lang="oz">fun {IsPalindrome S}
{Reverse S} == S
{Reverse S} == S
end</lang>
end</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>ispal(s)={
<syntaxhighlight lang="parigp">ispal(s)={
s=Vec(s);
s=Vec(s);
for(i=1,#v\2,
for(i=1,#v\2,
Line 3,663: Line 3,663:
);
);
1
1
};</lang>
};</syntaxhighlight>


A version for numbers:
A version for numbers:
{{works with|PARI/GP|2.6.0 and above}}
{{works with|PARI/GP|2.6.0 and above}}
<lang parigp>ispal(s)={
<syntaxhighlight lang="parigp">ispal(s)={
my(d=digits(n));
my(d=digits(n));
for(i=1,#d\2,
for(i=1,#d\2,
Line 3,673: Line 3,673:
);
);
1
1
};</lang>
};</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Free Pascal}}
{{works with|Free Pascal}}
<lang pascal>program Palindro;
<syntaxhighlight lang="pascal">program Palindro;


{ RECURSIVE }
{ RECURSIVE }
Line 3,699: Line 3,699:
else
else
is_palindro := false
is_palindro := false
end;</lang>
end;</syntaxhighlight>


<lang pascal>procedure test_r(s : String; r : Boolean);
<syntaxhighlight lang="pascal">procedure test_r(s : String; r : Boolean);
begin
begin
write('"', s, '" is ');
write('"', s, '" is ');
Line 3,719: Line 3,719:
test_r(s1, is_palindro(s1));
test_r(s1, is_palindro(s1));
test_r(s2, is_palindro(s2))
test_r(s2, is_palindro(s2))
end.</lang>
end.</syntaxhighlight>


<lang pascal>program PalindromeDetection;
<syntaxhighlight lang="pascal">program PalindromeDetection;
var
var
input, output: string;
input, output: string;
Line 3,739: Line 3,739:
else
else
writeln('input was not palindrome');
writeln('input was not palindrome');
end.</lang>
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Line 3,755: Line 3,755:
before you call these functions.
before you call these functions.


<lang perl># Palindrome.pm
<syntaxhighlight lang="perl"># Palindrome.pm
package Palindrome;
package Palindrome;


Line 3,791: Line 3,791:
{
{
(@_ ? shift : $_) =~ /^(.?|(.)(?1)\2)$/ + 0
(@_ ? shift : $_) =~ /^(.?|(.)(?1)\2)$/ + 0
}</lang>
}</syntaxhighlight>


This example shows how to use the functions:
This example shows how to use the functions:


<lang perl># pbench.pl
<syntaxhighlight lang="perl"># pbench.pl
use strict;
use strict;
use warnings;
use warnings;
Line 3,817: Line 3,817:
palindrome_r => sub { palindrome_r $latin },
palindrome_r => sub { palindrome_r $latin },
palindrome_e => sub { palindrome_e $latin },
palindrome_e => sub { palindrome_e $latin },
});</lang>
});</syntaxhighlight>


{{out}} on a machine running Perl 5.10.1 on amd64-openbsd:
{{out}} on a machine running Perl 5.10.1 on amd64-openbsd:
Line 3,845: Line 3,845:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">is_palindrome</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">is_palindrome</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">==</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">==</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 3,870: Line 3,870:
<span style="color: #0000FF;">?</span><span style="color: #000000;">extra_credit</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"가련하시다 사장집 아들딸들아 집장사 다시 하련가"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">extra_credit</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"가련하시다 사장집 아들딸들아 집장사 다시 하련가"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">extra_credit</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"tregða, gón, reiði - er nóg að gert"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">extra_credit</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"tregða, gón, reiði - er nóg að gert"</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
function is_palindrome($string) {
function is_palindrome($string) {
return $string == strrev($string);
return $string == strrev($string);
}
}
?></lang>
?></syntaxhighlight>


Regular expression-based solution ([http://www.polygenelubricants.com/2010/09/matching-palindromes-in-pcre-regex.html source])
Regular expression-based solution ([http://www.polygenelubricants.com/2010/09/matching-palindromes-in-pcre-regex.html source])
<lang php><?php
<syntaxhighlight lang="php"><?php
function is_palindrome($string) {
function is_palindrome($string) {
return preg_match('/^(?:(.)(?=.*(\1(?(2)\2|))$))*.?\2?$/', $string);
return preg_match('/^(?:(.)(?=.*(\1(?(2)\2|))$))*.?\2?$/', $string);
}
}
?></lang>
?></syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
Tests = ["In girum imus nocte et consumimur igni",
Tests = ["In girum imus nocte et consumimur igni",
"this is a non palindrome string",
"this is a non palindrome string",
Line 3,929: Line 3,929:
% skips punctuation and white space.
% skips punctuation and white space.
strip(S) = [C : C in S.to_lowercase(),
strip(S) = [C : C in S.to_lowercase(),
not C.membchk("!?,.;-_ \t\n()[]{}")].</lang>
not C.membchk("!?,.;-_ \t\n()[]{}")].</syntaxhighlight>


{{out}}
{{out}}
Line 3,945: Line 3,945:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de palindrome? (S)
<syntaxhighlight lang="picolisp">(de palindrome? (S)
(= (setq S (chop S)) (reverse S)) )</lang>
(= (setq S (chop S)) (reverse S)) )</syntaxhighlight>
{{out}}
{{out}}
<pre>: (palindrome? "ingirumimusnocteetconsumimurigni")
<pre>: (palindrome? "ingirumimusnocteetconsumimurigni")
Line 3,952: Line 3,952:


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>int main(){
<syntaxhighlight lang="pike">int main(){
if(pal("rotator")){
if(pal("rotator")){
write("palindrome!\n");
write("palindrome!\n");
Line 3,967: Line 3,967:
return 0;
return 0;
}
}
}</lang>
}</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
To satisfy the revised specification (which contradicts the preceding explanation)
To satisfy the revised specification (which contradicts the preceding explanation)
the following trivially solves the problem in PL/I:
the following trivially solves the problem in PL/I:
<lang PL/I>is_palindrome = (text = reverse(text));</lang>
<syntaxhighlight lang="pl/i">is_palindrome = (text = reverse(text));</syntaxhighlight>


The following solution strips spaces:
The following solution strips spaces:
<lang>is_palindrome: procedure (text) returns (bit(1));
<syntaxhighlight lang="text">is_palindrome: procedure (text) returns (bit(1));
declare text character (*) varying;
declare text character (*) varying;


Line 3,992: Line 3,992:
return (substr(text, 1, j));
return (substr(text, 1, j));
end remove_blanks;
end remove_blanks;
end is_palindrome;</lang>
end is_palindrome;</syntaxhighlight>


=={{header|PL/M}}==
=={{header|PL/M}}==
<lang plm>100H:
<syntaxhighlight lang="plm">100H:


/* CHECK EXACT PALINDROME ASSUMING $-TERMINATED STRING */
/* CHECK EXACT PALINDROME ASSUMING $-TERMINATED STRING */
Line 4,075: Line 4,075:


CALL BDOS(0,0);
CALL BDOS(0,0);
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>ROTOR: EXACT
<pre>ROTOR: EXACT
Line 4,094: Line 4,094:
<code>first</code> is an address, while <code>first's target</code> is the byte at that address.
<code>first</code> is an address, while <code>first's target</code> is the byte at that address.
No need to actually reverse the string; just compare the first's target with the last's target until they meet in the middle.
No need to actually reverse the string; just compare the first's target with the last's target until they meet in the middle.
<lang plainenglish>To decide if a string is palindromic:
<syntaxhighlight lang="plainenglish">To decide if a string is palindromic:
Slap a substring on the string.
Slap a substring on the string.
Loop.
Loop.
Line 4,101: Line 4,101:
Add 1 to the substring's first.
Add 1 to the substring's first.
Subtract 1 from the substring's last.
Subtract 1 from the substring's last.
Repeat.</lang>
Repeat.</syntaxhighlight>


=={{header|Pointless}}==
=={{header|Pointless}}==
'''Basic Function'''
'''Basic Function'''
<lang pointless>isPalindrome(chars) =
<syntaxhighlight lang="pointless">isPalindrome(chars) =
chars == reverse(chars)</lang>
chars == reverse(chars)</syntaxhighlight>


'''With Pre-processing'''
'''With Pre-processing'''
<lang pointless>output =
<syntaxhighlight lang="pointless">output =
"A man, a plan, a canal -- Panama"
"A man, a plan, a canal -- Panama"
|> toList
|> toList
Line 4,115: Line 4,115:
|> map(toLower)
|> map(toLower)
|> isPalindrome
|> isPalindrome
|> println</lang>
|> println</syntaxhighlight>


{{out}}
{{out}}
Line 4,121: Line 4,121:


=={{header|Potion}}==
=={{header|Potion}}==
<lang Potion># The readable recursive version
<syntaxhighlight lang="potion"># The readable recursive version
palindrome_i = (s, b, e):
palindrome_i = (s, b, e):
if (e <= b): true.
if (e <= b): true.
Line 4,131: Line 4,131:
palindrome_i(s, 0, s length - 1).
palindrome_i(s, 0, s length - 1).


palindrome(argv(1))</lang>
palindrome(argv(1))</syntaxhighlight>


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
Line 4,137: Line 4,137:
The output is identical to the [[#BASIC|QBasic]] version, above.
The output is identical to the [[#BASIC|QBasic]] version, above.


<lang powerbasic>FUNCTION isPalindrome (what AS STRING) AS LONG
<syntaxhighlight lang="powerbasic">FUNCTION isPalindrome (what AS STRING) AS LONG
DIM whatcopy AS STRING, chk AS STRING, tmp AS STRING * 1, L0 AS LONG
DIM whatcopy AS STRING, chk AS STRING, tmp AS STRING * 1, L0 AS LONG


Line 4,168: Line 4,168:
END IF
END IF
NEXT
NEXT
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
An exact version based on reversing the string:
An exact version based on reversing the string:
<syntaxhighlight lang="powershell">
<lang PowerShell>
Function Test-Palindrome( [String] $Text ){
Function Test-Palindrome( [String] $Text ){
$CharArray = $Text.ToCharArray()
$CharArray = $Text.ToCharArray()
Line 4,178: Line 4,178:
$Text -eq [string]::join('', $CharArray)
$Text -eq [string]::join('', $CharArray)
}
}
</syntaxhighlight>
</lang>
===PowerShell (Regex Version)===
===PowerShell (Regex Version)===
This version is much faster because it does not manipulate arrays. [This is not clear; the above version was slowed down by using -join instead of [string]::join, and -like instead of -eq. After changing those it is similar, if not faster, than this version].
This version is much faster because it does not manipulate arrays. [This is not clear; the above version was slowed down by using -join instead of [string]::join, and -like instead of -eq. After changing those it is similar, if not faster, than this version].
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Test-Palindrome
function Test-Palindrome
{
{
Line 4,216: Line 4,216:
$Text -match "^(?'char'[a-z])+[a-z]?(?:\k'char'(?'-char'))+(?(char)(?!))$"
$Text -match "^(?'char'[a-z])+[a-z]?(?:\k'char'(?'-char'))+(?(char)(?!))$"
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Test-Palindrome -Text 'radar'
Test-Palindrome -Text 'radar'
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
True
True
</pre>
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Test-Palindrome -Text "In girum imus nocte et consumimur igni."
Test-Palindrome -Text "In girum imus nocte et consumimur igni."
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
False
False
</pre>
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Test-Palindrome -Text "In girum imus nocte et consumimur igni." -Inexact
Test-Palindrome -Text "In girum imus nocte et consumimur igni." -Inexact
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,240: Line 4,240:
===PowerShell (Unicode category aware, no string reverse)===
===PowerShell (Unicode category aware, no string reverse)===
An inexact version can remove punctuation by looking at Unicode categories for each character, either using .Net methods or a regex.
An inexact version can remove punctuation by looking at Unicode categories for each character, either using .Net methods or a regex.
<lang PowerShell>Function Test-Palindrome {
<syntaxhighlight lang="powershell">Function Test-Palindrome {
[CmdletBinding()]
[CmdletBinding()]
Param(
Param(
Line 4,289: Line 4,289:
}
}
}
}
'ánu-ná', 'nowt' | Test-Palindrome</lang>
'ánu-ná', 'nowt' | Test-Palindrome</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,301: Line 4,301:


=={{header|Processing}}==
=={{header|Processing}}==
<lang processing>
<syntaxhighlight lang="processing">
void setup(){
void setup(){
println(isPalindrome(InsertPalindromeHere));
println(isPalindrome(InsertPalindromeHere));
Line 4,323: Line 4,323:
}
}
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,331: Line 4,331:


====Alternative Implementation: using StringBuilder, implementing exact and inexact check====
====Alternative Implementation: using StringBuilder, implementing exact and inexact check====
<lang processing>
<syntaxhighlight lang="processing">
void setup(){
void setup(){
println("PalindromeDetection");
println("PalindromeDetection");
Line 4,371: Line 4,371:
return isExactPalindrome(s.replaceAll("\\s+","").replaceAll("[^A-Za-z]+", "").toLowerCase());
return isExactPalindrome(s.replaceAll("\\s+","").replaceAll("[^A-Za-z]+", "").toLowerCase());
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,394: Line 4,394:
From [http://www2.dcs.hull.ac.uk/NEAT/dnd/AI/prolog/tutorial2.html this tutorial].
From [http://www2.dcs.hull.ac.uk/NEAT/dnd/AI/prolog/tutorial2.html this tutorial].


<lang prolog>palindrome(Word) :- name(Word,List), reverse(List,List).</lang>
<syntaxhighlight lang="prolog">palindrome(Word) :- name(Word,List), reverse(List,List).</syntaxhighlight>


'''Recursive'''
'''Recursive'''


{{works with|SWI Prolog}}
{{works with|SWI Prolog}}
<lang prolog>pali(Str) :- sub_string(Str, 0, 1, _, X), string_concat(Str2, X, Str), string_concat(X, Mid, Str2), pali(Mid).
<syntaxhighlight lang="prolog">pali(Str) :- sub_string(Str, 0, 1, _, X), string_concat(Str2, X, Str), string_concat(X, Mid, Str2), pali(Mid).
pali(Str) :- string_length(Str, Len), Len < 2.</lang>
pali(Str) :- string_length(Str, Len), Len < 2.</syntaxhighlight>


Changing '''string''' into '''atom''' makes the program run also on GNU Prolog. I.e.
Changing '''string''' into '''atom''' makes the program run also on GNU Prolog. I.e.
Line 4,406: Line 4,406:
{{works with|GNU Prolog}}
{{works with|GNU Prolog}}


<lang prolog>pali(Str) :- sub_atom(Str, 0, 1, _, X), atom_concat(Str2, X, Str), atom_concat(X, Mid, Str2), pali(Mid).
<syntaxhighlight lang="prolog">pali(Str) :- sub_atom(Str, 0, 1, _, X), atom_concat(Str2, X, Str), atom_concat(X, Mid, Str2), pali(Mid).
pali(Str) :- atom_length(Str, Len), Len < 2.</lang>
pali(Str) :- atom_length(Str, Len), Len < 2.</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
{{works with|PureBasic|4.41}}
{{works with|PureBasic|4.41}}
<lang PureBasic>Procedure IsPalindrome(StringToTest.s)
<syntaxhighlight lang="purebasic">Procedure IsPalindrome(StringToTest.s)
If StringToTest=ReverseString(StringToTest)
If StringToTest=ReverseString(StringToTest)
ProcedureReturn 1
ProcedureReturn 1
Line 4,417: Line 4,417:
ProcedureReturn 0
ProcedureReturn 0
EndIf
EndIf
EndProcedure</lang>
EndProcedure</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 4,428: Line 4,428:
but right syntax <tt>string[::-1]</tt>)
but right syntax <tt>string[::-1]</tt>)


<lang python>def is_palindrome(s):
<syntaxhighlight lang="python">def is_palindrome(s):
return s == s[::-1]</lang>
return s == s[::-1]</syntaxhighlight>


'''Non-recursive, Ignoring Punctuation/Case/Spaces'''
'''Non-recursive, Ignoring Punctuation/Case/Spaces'''
Line 4,435: Line 4,435:
A word is a palindrome if the letters are the same forwards as backwards, but the other methods given here will return False for, e.g., an input of "Go hang a salami, I'm a lasagna hog" or "A man, a plan, a canal: Panama." An implementation that traverses the string and ignores case differences, spaces, and non-alpha characters is pretty trivial.
A word is a palindrome if the letters are the same forwards as backwards, but the other methods given here will return False for, e.g., an input of "Go hang a salami, I'm a lasagna hog" or "A man, a plan, a canal: Panama." An implementation that traverses the string and ignores case differences, spaces, and non-alpha characters is pretty trivial.


<lang python>def is_palindrome(s):
<syntaxhighlight lang="python">def is_palindrome(s):
low = 0
low = 0
high = len(s) - 1
high = len(s) - 1
Line 4,449: Line 4,449:
low += 1
low += 1
high -= 1
high -= 1
return True</lang>
return True</syntaxhighlight>


'''Recursive'''
'''Recursive'''


<lang python>def is_palindrome_r(s):
<syntaxhighlight lang="python">def is_palindrome_r(s):
if len(s) <= 1:
if len(s) <= 1:
return True
return True
Line 4,459: Line 4,459:
return False
return False
else:
else:
return is_palindrome_r(s[1:-1])</lang>
return is_palindrome_r(s[1:-1])</syntaxhighlight>


Python has short-circuit evaluation of Boolean operations
Python has short-circuit evaluation of Boolean operations
so a shorter and still easy to understand recursive function is
so a shorter and still easy to understand recursive function is


<lang python>def is_palindrome_r2(s):
<syntaxhighlight lang="python">def is_palindrome_r2(s):
return not s or s[0] == s[-1] and is_palindrome_r2(s[1:-1])</lang>
return not s or s[0] == s[-1] and is_palindrome_r2(s[1:-1])</syntaxhighlight>


'''Testing'''
'''Testing'''


<lang python>def test(f, good, bad):
<syntaxhighlight lang="python">def test(f, good, bad):
assert all(f(x) for x in good)
assert all(f(x) for x in good)
assert not any(f(x) for x in bad)
assert not any(f(x) for x in bad)
Line 4,477: Line 4,477:
notpals = ('aA', 'abA', 'abxBa', 'abxxBa')
notpals = ('aA', 'abA', 'abxBa', 'abxxBa')
for ispal in is_palindrome, is_palindrome_r, is_palindrome_r2:
for ispal in is_palindrome, is_palindrome_r, is_palindrome_r2:
test(ispal, pals, notpals)</lang>
test(ispal, pals, notpals)</syntaxhighlight>


''' Palindrome Using Regular Expressions Python 2.7 '''
''' Palindrome Using Regular Expressions Python 2.7 '''


<lang python>def p_loop():
<syntaxhighlight lang="python">def p_loop():
import re, string
import re, string
re1="" # Beginning of Regex
re1="" # Beginning of Regex
Line 4,508: Line 4,508:
else:
else:
print("Nope!")
print("Nope!")
return 0</lang>
return 0</syntaxhighlight>




'''Checking the left half against a reflection of the right half'''
'''Checking the left half against a reflection of the right half'''
<lang python>'''Palindrome detection'''
<syntaxhighlight lang="python">'''Palindrome detection'''




Line 4,550: Line 4,550:
if __name__ == '__main__':
if __name__ == '__main__':
main()
main()
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>'' -> True
<pre>'' -> True
Line 4,573: Line 4,573:
-5 -4 -3 -2 -1 <-- negative index</pre>
-5 -4 -3 -2 -1 <-- negative index</pre>


<lang Python>def palindromic(str):
<syntaxhighlight lang="python">def palindromic(str):
for i in range(len(str)//2):
for i in range(len(str)//2):
if str[i] != str[~i]:
if str[i] != str[~i]:
return(False)
return(False)
return(True)</lang>
return(True)</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ dup reverse = ] is palindromic ( [ --> b )
<syntaxhighlight lang="quackery"> [ dup reverse = ] is palindromic ( [ --> b )


[ [] swap witheach
[ [] swap witheach
Line 4,587: Line 4,587:
dup lower = iff
dup lower = iff
drop else join ]
drop else join ]
palindromic ] is inexactpalindrome ( $ --> b )</lang>
palindromic ] is inexactpalindrome ( $ --> b )</syntaxhighlight>


===Twiddle Indexing===
===Twiddle Indexing===


<lang Quackery> [ true swap
<syntaxhighlight lang="quackery"> [ true swap
dup size 2 / times
dup size 2 / times
[ dup i peek
[ dup i peek
over i ~ peek != if
over i ~ peek != if
[ dip not conclude ] ]
[ dip not conclude ] ]
drop ] is palindromic ( [ --> b )</lang>
drop ] is palindromic ( [ --> b )</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
Line 4,604: Line 4,604:
R will assume an infinite recursion if a recursion nests deeper than 5,000.
R will assume an infinite recursion if a recursion nests deeper than 5,000.
Options may be set in the environment to increase this to 500,000.
Options may be set in the environment to increase this to 500,000.
<lang rsplus>palindro <- function(p) {
<syntaxhighlight lang="rsplus">palindro <- function(p) {
if ( nchar(p) == 1 ) {
if ( nchar(p) == 1 ) {
return(TRUE)
return(TRUE)
Line 4,616: Line 4,616:
}
}
}
}
}</lang>
}</syntaxhighlight>


'''Iterative'''
'''Iterative'''
<lang rsplus>palindroi <- function(p) {
<syntaxhighlight lang="rsplus">palindroi <- function(p) {
for(i in 1:floor(nchar(p)/2) ) {
for(i in 1:floor(nchar(p)/2) ) {
r <- nchar(p) - i + 1
r <- nchar(p) - i + 1
Line 4,625: Line 4,625:
}
}
TRUE
TRUE
}</lang>
}</syntaxhighlight>


'''Comparative'''
'''Comparative'''
Line 4,633: Line 4,633:
Note that this method incorrectly regards an empty string as not a palindrome.
Note that this method incorrectly regards an empty string as not a palindrome.
Please leave this bug in the code, and take a look a the [[Testing_a_Function]] page.
Please leave this bug in the code, and take a look a the [[Testing_a_Function]] page.
<lang rsplus>revstring <- function(stringtorev) {
<syntaxhighlight lang="rsplus">revstring <- function(stringtorev) {
return(
return(
paste(
paste(
Line 4,640: Line 4,640:
)
)
}
}
palindroc <- function(p) {return(revstring(p)==p)}</lang>
palindroc <- function(p) {return(revstring(p)==p)}</syntaxhighlight>


'''Rev'''
'''Rev'''
Line 4,647: Line 4,647:


Unicode is supported, but this ignores the "inexact palindromes" extra credit requirement because, without some sort of regex, supporting Unicode while stripping punctuation and white space is hard in R.
Unicode is supported, but this ignores the "inexact palindromes" extra credit requirement because, without some sort of regex, supporting Unicode while stripping punctuation and white space is hard in R.
<lang rsplus>is.Palindrome <- function(string)
<syntaxhighlight lang="rsplus">is.Palindrome <- function(string)
{
{
characters <- unlist(strsplit(string, ""))
characters <- unlist(strsplit(string, ""))
all(characters == rev(characters))
all(characters == rev(characters))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
The rev solution is not benchmarked.
The rev solution is not benchmarked.
Line 4,672: Line 4,672:
=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
(define (palindromb str)
(define (palindromb str)
(let* ([lst (string->list (string-downcase str))]
(let* ([lst (string->list (string-downcase str))]
Line 4,687: Line 4,687:
#t
#t
>
>
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>subset Palindrom of Str where {
<syntaxhighlight lang="raku" line>subset Palindrom of Str where {
.flip eq $_ given .comb(/\w+/).join.lc
.flip eq $_ given .comb(/\w+/).join.lc
}
}
Line 4,703: Line 4,703:
END
END
for @tests { say $_ ~~ Palindrom, "\t", $_ }</lang>
for @tests { say $_ ~~ Palindrom, "\t", $_ }</syntaxhighlight>
{{out}}
{{out}}
<pre>True A man, a plan, a canal: Panama.
<pre>True A man, a plan, a canal: Panama.
Line 4,714: Line 4,714:
=={{header|Rascal}}==
=={{header|Rascal}}==
The most simple solution:
The most simple solution:
<lang rascal>import String;
<syntaxhighlight lang="rascal">import String;


public bool palindrome(str text) = toLowerCase(text) == reverse(text);</lang>
public bool palindrome(str text) = toLowerCase(text) == reverse(text);</syntaxhighlight>


A solution that handles sentences with spaces and capitals:
A solution that handles sentences with spaces and capitals:


<lang rascal>import String;
<syntaxhighlight lang="rascal">import String;


public bool palindrome(str text){
public bool palindrome(str text){
Line 4,726: Line 4,726:
return text == reverse(text);
return text == reverse(text);
}
}
</syntaxhighlight>
</lang>


Example:
Example:
<lang rascal>rascal>palindrome("In girum imus nocte et consumimur igni")
<syntaxhighlight lang="rascal">rascal>palindrome("In girum imus nocte et consumimur igni")
bool: true</lang>
bool: true</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==


<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Palindrome Recognizer"
Title: "Palindrome Recognizer"
URL: http://rosettacode.org/wiki/Palindrome
URL: http://rosettacode.org/wiki/Palindrome
Line 4,762: Line 4,762:
assert [palindrome? "In girum imus nocte et consumimur igni"] ; Spaces not removed.
assert [palindrome? "In girum imus nocte et consumimur igni"] ; Spaces not removed.


; I know we're doing palindromes, not alliteration, but who could resist...?</lang>
; I know we're doing palindromes, not alliteration, but who could resist...?</syntaxhighlight>


{{out}}
{{out}}
Line 4,778: Line 4,778:
=={{header|Retro}}==
=={{header|Retro}}==


<syntaxhighlight lang="retro">
<lang Retro>
:palindrome? (s-f) dup s:hash [ s:reverse s:hash ] dip eq? ;
:palindrome? (s-f) dup s:hash [ s:reverse s:hash ] dip eq? ;


'ingirumimusnocteetconsumimurigni palindrome? n:put
'ingirumimusnocteetconsumimurigni palindrome? n:put
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang REXX>/*REXX pgm checks if phrase is palindromic; ignores the case of the letters. */
<syntaxhighlight lang="rexx">/*REXX pgm checks if phrase is palindromic; ignores the case of the letters. */
parse arg y /*get (optional) phrase from the C.L. */
parse arg y /*get (optional) phrase from the C.L. */
if y='' then y='In girum imus nocte et consumimur igni' /*[↓] translation.*/
if y='' then y='In girum imus nocte et consumimur igni' /*[↓] translation.*/
Line 4,797: Line 4,797:
/*────────────────────────────────────────────────────────────────────────────*/
/*────────────────────────────────────────────────────────────────────────────*/
isTpal: return reverse(arg(1))==arg(1)
isTpal: return reverse(arg(1))==arg(1)
isPal: return isTpal(translate(space(x,0)))</lang>
isPal: return isTpal(translate(space(x,0)))</syntaxhighlight>
{{out|output|text=''':'''}}
{{out|output|text=''':'''}}
<pre>
<pre>
Line 4,815: Line 4,815:
It should also be noted that &nbsp; '''UPPER''' &nbsp; BIF is not present in some REXXes.
It should also be noted that &nbsp; '''UPPER''' &nbsp; BIF is not present in some REXXes.
<br>Use the &nbsp; '''PARSE UPPER''' &nbsp; statement or &nbsp; '''TRANSLATE()''' &nbsp; BIF instead.
<br>Use the &nbsp; '''PARSE UPPER''' &nbsp; statement or &nbsp; '''TRANSLATE()''' &nbsp; BIF instead.
<syntaxhighlight lang="rexx">
<lang REXX>
/* REXX */
/* REXX */


Line 4,830: Line 4,830:
parse arg string
parse arg string
return string==reverse(string)
return string==reverse(string)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,839: Line 4,839:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
aString = "radar"
aString = "radar"
bString = ""
bString = ""
Line 4,848: Line 4,848:
if aString = bString see " is a palindrome." + nl
if aString = bString see " is a palindrome." + nl
else see " is not a palindrome" + nl ok
else see " is not a palindrome" + nl ok
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Line 4,854: Line 4,854:
'''Non-recursive'''
'''Non-recursive'''


<lang ruby>def palindrome?(s)
<syntaxhighlight lang="ruby">def palindrome?(s)
s == s.reverse
s == s.reverse
end</lang>
end</syntaxhighlight>


'''Recursive'''
'''Recursive'''


<lang ruby>def r_palindrome?(s)
<syntaxhighlight lang="ruby">def r_palindrome?(s)
if s.length <= 1
if s.length <= 1
true
true
Line 4,868: Line 4,868:
r_palindrome?(s[1..-2])
r_palindrome?(s[1..-2])
end
end
end</lang>
end</syntaxhighlight>


'''Testing'''
'''Testing'''
Note that the recursive method is ''much'' slower -- using the 2151 character palindrome by Dan Hoey [http://www2.vo.lu/homepages/phahn/anagrams/panama.htm here], we have:
Note that the recursive method is ''much'' slower -- using the 2151 character palindrome by Dan Hoey [http://www2.vo.lu/homepages/phahn/anagrams/panama.htm here], we have:
<lang ruby>str = "A man, a plan, a caret, [...2110 chars deleted...] a canal--Panama.".downcase.delete('^a-z')
<syntaxhighlight lang="ruby">str = "A man, a plan, a caret, [...2110 chars deleted...] a canal--Panama.".downcase.delete('^a-z')
puts palindrome?(str) # => true
puts palindrome?(str) # => true
puts r_palindrome?(str) # => true
puts r_palindrome?(str) # => true
Line 4,880: Line 4,880:
b.report('iterative') {10000.times {palindrome?(str)}}
b.report('iterative') {10000.times {palindrome?(str)}}
b.report('recursive') {10000.times {r_palindrome?(str)}}
b.report('recursive') {10000.times {r_palindrome?(str)}}
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 4,890: Line 4,890:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>data "My dog has fleas", "Madam, I'm Adam.", "1 on 1", "In girum imus nocte et consumimur igni"
<syntaxhighlight lang="runbasic">data "My dog has fleas", "Madam, I'm Adam.", "1 on 1", "In girum imus nocte et consumimur igni"
for i = 1 to 4
for i = 1 to 4
Line 4,902: Line 4,902:
if (a$ >= "A" and a$ <= "Z") or (a$ >= "0" and a$ <= "9") then b$ = b$ + a$: c$ = a$ + c$
if (a$ >= "A" and a$ <= "Z") or (a$ >= "0" and a$ <= "9") then b$ = b$ + a$: c$ = a$ + c$
next i
next i
if b$ <> c$ then isPalindrome$ = "not"</lang>
if b$ <> c$ then isPalindrome$ = "not"</syntaxhighlight>
{{out}}
{{out}}
<pre>My dog has fleas is not Palindrome
<pre>My dog has fleas is not Palindrome
Line 4,910: Line 4,910:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn is_palindrome(string: &str) -> bool {
<syntaxhighlight lang="rust">fn is_palindrome(string: &str) -> bool {
let half_len = string.len() / 2;
let half_len = string.len() / 2;
string
string
Line 4,934: Line 4,934:
"The quick brown fox"
"The quick brown fox"
);
);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,948: Line 4,948:
</pre>
</pre>
The above soluion checks if the codepoints form a pallindrome, but it is perhaps more correct to consider if the graphemes form a pallindrome. This can be accomplished with an external library and a slight modification to <code>is_palindrome</code>.
The above soluion checks if the codepoints form a pallindrome, but it is perhaps more correct to consider if the graphemes form a pallindrome. This can be accomplished with an external library and a slight modification to <code>is_palindrome</code>.
<lang rust>extern crate unicode_segmentation;
<syntaxhighlight lang="rust">extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
use unicode_segmentation::UnicodeSegmentation;
fn is_palindrome(string: &str) -> bool {
fn is_palindrome(string: &str) -> bool {
string.graphemes(true).eq(string.graphemes(true).rev())
string.graphemes(true).eq(string.graphemes(true).rev())
}</lang>
}</syntaxhighlight>


=={{header|SAS}}==
=={{header|SAS}}==
Description
Description
<syntaxhighlight lang="sas">
<lang SAS>
The macro "palindro" has two parameters: string and ignorewhitespace.
The macro "palindro" has two parameters: string and ignorewhitespace.
string is the expression to be checked.
string is the expression to be checked.
Line 4,962: Line 4,962:
This macro was written in SAS 9.2. If you use a version before SAS 9.1.3,
This macro was written in SAS 9.2. If you use a version before SAS 9.1.3,
the compress function options will not work.
the compress function options will not work.
</syntaxhighlight>
</lang>
Code
Code
<syntaxhighlight lang="sas">
<lang SAS>
%MACRO palindro(string, ignorewhitespace);
%MACRO palindro(string, ignorewhitespace);
DATA _NULL_;
DATA _NULL_;
Line 4,989: Line 4,989:
RUN;
RUN;
%MEND;
%MEND;
</syntaxhighlight>
</lang>
Example macro call and output
Example macro call and output
<syntaxhighlight lang="sas">
<lang SAS>
%palindro("a man, a plan, a canal: panama",y);
%palindro("a man, a plan, a canal: panama",y);


Line 5,007: Line 5,007:
real time 0.00 seconds
real time 0.00 seconds
cpu time 0.00 seconds
cpu time 0.00 seconds
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
=== Non-recursive, robustified===
=== Non-recursive, robustified===
<lang Scala> def isPalindrome(s: String): Boolean = (s.size >= 2) && s == s.reverse</lang>
<syntaxhighlight lang="scala"> def isPalindrome(s: String): Boolean = (s.size >= 2) && s == s.reverse</syntaxhighlight>
===Bonus: Detect and account for odd space and punctuation===
===Bonus: Detect and account for odd space and punctuation===
<lang scala> def isPalindromeSentence(s: String): Boolean =
<syntaxhighlight lang="scala"> def isPalindromeSentence(s: String): Boolean =
(s.size >= 2) && {
(s.size >= 2) && {
val p = s.replaceAll("[^\\p{L}]", "").toLowerCase
val p = s.replaceAll("[^\\p{L}]", "").toLowerCase
p == p.reverse
p == p.reverse
}
}
</syntaxhighlight>
</lang>


===Recursive===
===Recursive===
<lang Scala>import scala.annotation.tailrec
<syntaxhighlight lang="scala">import scala.annotation.tailrec


def isPalindromeRec(s: String) = {
def isPalindromeRec(s: String) = {
Line 5,030: Line 5,030:


(s.size >= 2) && inner(s)
(s.size >= 2) && inner(s)
}</lang>
}</syntaxhighlight>
'''Testing'''
'''Testing'''
<lang Scala> // Testing
<syntaxhighlight lang="scala"> // Testing
assert(!isPalindrome(""))
assert(!isPalindrome(""))
assert(!isPalindrome("z"))
assert(!isPalindrome("z"))
Line 5,054: Line 5,054:
assert(!isPalindromeRec("A man a plan a canal Panama."))
assert(!isPalindromeRec("A man a plan a canal Panama."))


println("Successfully completed without errors.")</lang>
println("Successfully completed without errors.")</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
'''Non-recursive'''
'''Non-recursive'''


<lang scheme>(define (palindrome? s)
<syntaxhighlight lang="scheme">(define (palindrome? s)
(let ((chars (string->list s)))
(let ((chars (string->list s)))
(equal? chars (reverse chars))))</lang>
(equal? chars (reverse chars))))</syntaxhighlight>


'''Recursive'''
'''Recursive'''
<lang scheme>(define (palindrome? s)
<syntaxhighlight lang="scheme">(define (palindrome? s)
(let loop ((i 0)
(let loop ((i 0)
(j (- (string-length s) 1)))
(j (- (string-length s) 1)))
Line 5,083: Line 5,083:
> (palindrome? "This is not a palindrome")
> (palindrome? "This is not a palindrome")
#f
#f
></lang>
></syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>const func boolean: palindrome (in string: stri) is func
<syntaxhighlight lang="seed7">const func boolean: palindrome (in string: stri) is func
result
result
var boolean: isPalindrome is TRUE;
var boolean: isPalindrome is TRUE;
Line 5,099: Line 5,099:
end if;
end if;
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


For palindromes where spaces shuld be ignore use:
For palindromes where spaces shuld be ignore use:
<lang seed7>palindrome(replace("in girum imus nocte et consumimur igni", " ", ""))</lang>
<syntaxhighlight lang="seed7">palindrome(replace("in girum imus nocte et consumimur igni", " ", ""))</syntaxhighlight>


=={{header|SequenceL}}==
=={{header|SequenceL}}==
'''Using the Reverse Library Function'''
'''Using the Reverse Library Function'''
<lang sequencel>import <Utilities/Sequence.sl>;
<syntaxhighlight lang="sequencel">import <Utilities/Sequence.sl>;


isPalindrome(string(1)) := equalList(string, reverse(string));</lang>
isPalindrome(string(1)) := equalList(string, reverse(string));</syntaxhighlight>


'''Version Using an Indexed Function'''
'''Version Using an Indexed Function'''
<lang sequencel>isPalindrome(string(1)) :=
<syntaxhighlight lang="sequencel">isPalindrome(string(1)) :=
let
let
compares[i] := string[i] = string[size(string) - (i - 1)] foreach i within 1 ... (size(string) / 2);
compares[i] := string[i] = string[size(string) - (i - 1)] foreach i within 1 ... (size(string) / 2);
in
in
all(compares);</lang>
all(compares);</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==


'''Built-in'''
'''Built-in'''
<lang ruby>say "noon".is_palindrome; # true</lang>
<syntaxhighlight lang="ruby">say "noon".is_palindrome; # true</syntaxhighlight>


'''Non-recursive'''
'''Non-recursive'''


<lang ruby>func palindrome(s) {
<syntaxhighlight lang="ruby">func palindrome(s) {
s == s.reverse
s == s.reverse
}</lang>
}</syntaxhighlight>


'''Recursive'''
'''Recursive'''


<lang ruby>func palindrome(s) {
<syntaxhighlight lang="ruby">func palindrome(s) {
if (s.len <= 1) {
if (s.len <= 1) {
true
true
Line 5,140: Line 5,140:
__FUNC__(s.ft(1, -2))
__FUNC__(s.ft(1, -2))
}
}
}</lang>
}</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BEGIN
<syntaxhighlight lang="simula">BEGIN


BOOLEAN PROCEDURE ISPALINDROME(T); TEXT T;
BOOLEAN PROCEDURE ISPALINDROME(T); TEXT T;
Line 5,175: Line 5,175:
END;
END;


END.</lang>
END.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,191: Line 5,191:
=={{header|Slate}}==
=={{header|Slate}}==
'''Non-Recursive'''
'''Non-Recursive'''
<lang slate>s@(String traits) isPalindrome
<syntaxhighlight lang="slate">s@(String traits) isPalindrome
[
[
(s lexicographicallyCompare: s reversed) isZero
(s lexicographicallyCompare: s reversed) isZero
].</lang>
].</syntaxhighlight>


'''Recursive'''
'''Recursive'''
Defined on Sequence since we are not using String-specific methods:
Defined on Sequence since we are not using String-specific methods:
<lang slate>s@(Sequence traits) isPalindrome
<syntaxhighlight lang="slate">s@(Sequence traits) isPalindrome
[
[
s isEmpty
s isEmpty
ifTrue: [True]
ifTrue: [True]
ifFalse: [(s first = s last) /\ [(s sliceFrom: 1 to: s indexLast - 1) isPalindrome]]
ifFalse: [(s first = s last) /\ [(s sliceFrom: 1 to: s indexLast - 1) isPalindrome]]
].</lang>
].</syntaxhighlight>


'''Testing'''
'''Testing'''
<lang slate>define: #p -> 'ingirumimusnocteetconsumimurigni'.
<syntaxhighlight lang="slate">define: #p -> 'ingirumimusnocteetconsumimurigni'.
inform: 'sequence ' ; p ; ' is ' ; (p isPalindrome ifTrue: [''] ifFalse: ['not ']) ; 'a palindrome.'.</lang>
inform: 'sequence ' ; p ; ' is ' ; (p isPalindrome ifTrue: [''] ifFalse: ['not ']) ; 'a palindrome.'.</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==


{{works with|Squeak}}
{{works with|Squeak}}
<lang smalltalk>isPalindrome := [:aString |
<syntaxhighlight lang="smalltalk">isPalindrome := [:aString |
str := (aString select: [:chr| chr isAlphaNumeric]) collect: [:chr | chr asLowercase].
str := (aString select: [:chr| chr isAlphaNumeric]) collect: [:chr | chr asLowercase].
str = str reversed.
str = str reversed.
].
].
</syntaxhighlight>
</lang>


{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
<lang smalltalk>String extend [
<syntaxhighlight lang="smalltalk">String extend [
palindro [ "Non-recursive"
palindro [ "Non-recursive"
^ self = (self reverse)
^ self = (self reverse)
Line 5,232: Line 5,232:
]
]
]
]
].</lang>
].</syntaxhighlight>


'''Testing'''
'''Testing'''


<lang smalltalk>('hello' palindro) printNl.
<syntaxhighlight lang="smalltalk">('hello' palindro) printNl.
('hello' palindroR) printNl.
('hello' palindroR) printNl.
('ingirumimusnocteetconsumimurigni' palindro) printNl.
('ingirumimusnocteetconsumimurigni' palindro) printNl.
('ingirumimusnocteetconsumimurigni' palindroR) printNl.</lang>
('ingirumimusnocteetconsumimurigni' palindroR) printNl.</syntaxhighlight>


{{works with|VisualWorks Pharo Squeak}}
{{works with|VisualWorks Pharo Squeak}}
<lang smalltalk>SequenceableCollection>>isPalindrome
<syntaxhighlight lang="smalltalk">SequenceableCollection>>isPalindrome
^self reverse = self
^self reverse = self
</syntaxhighlight>
</lang>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==


<lang SNOBOL4> define('pal(str)') :(pal_end)
<syntaxhighlight lang="snobol4"> define('pal(str)') :(pal_end)
pal str notany(&ucase &lcase) = :s(pal)
pal str notany(&ucase &lcase) = :s(pal)
str = replace(str,&ucase,&lcase)
str = replace(str,&ucase,&lcase)
Line 5,264: Line 5,264:
palchk('In girum imus nocte et consumimur igni')
palchk('In girum imus nocte et consumimur igni')
palchk('The quick brown fox jumped over the lazy dogs')
palchk('The quick brown fox jumped over the lazy dogs')
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 5,275: Line 5,275:


=={{header|SQL}}==
=={{header|SQL}}==
<lang sql>SET @txt = REPLACE('In girum imus nocte et consumimur igni', ' ', '');
<syntaxhighlight lang="sql">SET @txt = REPLACE('In girum imus nocte et consumimur igni', ' ', '');
SELECT REVERSE(@txt) = @txt;</lang>
SELECT REVERSE(@txt) = @txt;</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
{{works with|Swift|1.2}}
{{works with|Swift|1.2}}
<lang Swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


// Allow for easy character checking
// Allow for easy character checking
Line 5,298: Line 5,298:
}
}
return false
return false
}</lang>
}</syntaxhighlight>


{{works with|Swift|2.0}}
{{works with|Swift|2.0}}
<lang swift>func isPal(str: String) -> Bool {
<syntaxhighlight lang="swift">func isPal(str: String) -> Bool {
let c = str.characters
let c = str.characters
return lazy(c).reverse()
return lazy(c).reverse()
.startsWith(c[c.startIndex...advance(c.startIndex, c.count / 2)])
.startsWith(c[c.startIndex...advance(c.startIndex, c.count / 2)])
}</lang>
}</syntaxhighlight>


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang="tailspin">
templates palindrome
templates palindrome
[$...] -> #
[$...] -> #
Line 5,315: Line 5,315:


[['rotor', 'racecar', 'level', 'rosetta']... -> palindrome ] -> !OUT::write
[['rotor', 'racecar', 'level', 'rosetta']... -> palindrome ] -> !OUT::write
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,326: Line 5,326:
'''Non-recursive'''
'''Non-recursive'''


<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
proc palindrome {s} {
proc palindrome {s} {
return [expr {$s eq [string reverse $s]}]
return [expr {$s eq [string reverse $s]}]
}</lang>
}</syntaxhighlight>


'''Recursive'''
'''Recursive'''


<lang tcl>proc palindrome_r {s} {
<syntaxhighlight lang="tcl">proc palindrome_r {s} {
if {[string length $s] <= 1} {
if {[string length $s] <= 1} {
return true
return true
Line 5,341: Line 5,341:
return [palindrome_r [string range $s 1 end-1]]
return [palindrome_r [string range $s 1 end-1]]
}
}
}</lang>
}</syntaxhighlight>


'''Testing'''
'''Testing'''


<lang tcl>set p ingirumimusnocteetconsumimurigni
<syntaxhighlight lang="tcl">set p ingirumimusnocteetconsumimurigni
puts "'$p' is palindrome? [palindrome $p]"
puts "'$p' is palindrome? [palindrome $p]"
puts "'$p' is palindrome? [palindrome_r $p]"</lang>
puts "'$p' is palindrome? [palindrome_r $p]"</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
pal ="ingirumimusnocteetconsumimurigni"
pal ="ingirumimusnocteetconsumimurigni"
Line 5,360: Line 5,360:
PRINT/ERROR "untrue"
PRINT/ERROR "untrue"
ENDSELECT
ENDSELECT
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,367: Line 5,367:


=={{header|TypeScript}}==
=={{header|TypeScript}}==
<lang javascript>const detectNonLetterRegexp=/[^A-ZÀ-ÞЀ-Я]/g;
<syntaxhighlight lang="javascript">const detectNonLetterRegexp=/[^A-ZÀ-ÞЀ-Я]/g;


function stripDiacritics(phrase:string){
function stripDiacritics(phrase:string){
Line 5,384: Line 5,384:
console.log(isPalindrome('Dábale arroz a la zorra el abad!'))
console.log(isPalindrome('Dábale arroz a la zorra el abad!'))
console.log(isPalindrome('Я иду с мечем судия'))
console.log(isPalindrome('Я иду с мечем судия'))
</syntaxhighlight>
</lang>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>if [[ "${text}" == "$(rev <<< "${text}")" ]]; then
<syntaxhighlight lang="bash">if [[ "${text}" == "$(rev <<< "${text}")" ]]; then
echo "Palindrome"
echo "Palindrome"
else
else
echo "Not a palindrome"
echo "Not a palindrome"
fi</lang>
fi</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 5,400: Line 5,400:
This is done using the built in operator suffixes
This is done using the built in operator suffixes
for intersection (c), identity (i), reversal (x) and equality (E).
for intersection (c), identity (i), reversal (x) and equality (E).
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std


palindrome = ~&cixE\letters+ * -:~& ~=`A-~rlp letters</lang>
palindrome = ~&cixE\letters+ * -:~& ~=`A-~rlp letters</syntaxhighlight>
This test programs applies the function to each member of a list of three strings,
This test programs applies the function to each member of a list of three strings,
of which only the first two are palindromes.
of which only the first two are palindromes.
<lang Ursala>#cast %bL
<syntaxhighlight lang="ursala">#cast %bL


examples = palindrome* <'abccba','foo ba rra bo of','notone'></lang>
examples = palindrome* <'abccba','foo ba rra bo of','notone'></syntaxhighlight>
{{out}}
{{out}}
<pre><true,true,false></pre>
<pre><true,true,false></pre>
Line 5,413: Line 5,413:
=={{header|Vala}}==
=={{header|Vala}}==
Checks if a word is a palindrome ignoring the case and spaces.
Checks if a word is a palindrome ignoring the case and spaces.
<lang vala>bool is_palindrome (string str) {
<syntaxhighlight lang="vala">bool is_palindrome (string str) {
var tmp = str.casefold ().replace (" ", "");
var tmp = str.casefold ().replace (" ", "");
return tmp == tmp.reverse ();
return tmp == tmp.reverse ();
Line 5,421: Line 5,421:
print (is_palindrome (args[1]).to_string () + "\n");
print (is_palindrome (args[1]).to_string () + "\n");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
Line 5,429: Line 5,429:
version it could also work using StrReverse.
version it could also work using StrReverse.


<syntaxhighlight lang="vba">
<lang VBA>
Public Function isPalindrome(aString as string) as Boolean
Public Function isPalindrome(aString as string) as Boolean
dim tempstring as string
dim tempstring as string
Line 5,435: Line 5,435:
isPalindrome = (tempstring = Reverse(tempstring))
isPalindrome = (tempstring = Reverse(tempstring))
End Function
End Function
</syntaxhighlight>
</lang>


{{out|Example}}
{{out|Example}}
Line 5,445: Line 5,445:
=={{header|VBScript}}==
=={{header|VBScript}}==
====Implementation====
====Implementation====
<lang vb>function Squish( s1 )
<syntaxhighlight lang="vb">function Squish( s1 )
dim sRes
dim sRes
sRes = vbNullString
sRes = vbNullString
Line 5,462: Line 5,462:
squished = Squish( s1 )
squished = Squish( s1 )
isPalindrome = ( squished = StrReverse( squished ) )
isPalindrome = ( squished = StrReverse( squished ) )
end function</lang>
end function</syntaxhighlight>


====Invocation====
====Invocation====
<lang vb>wscript.echo isPalindrome( "My dog has fleas")
<syntaxhighlight lang="vb">wscript.echo isPalindrome( "My dog has fleas")
wscript.echo isPalindrome( "Madam, I'm Adam.")
wscript.echo isPalindrome( "Madam, I'm Adam.")
wscript.echo isPalindrome( "1 on 1")
wscript.echo isPalindrome( "1 on 1")
wscript.echo isPalindrome( "In girum imus nocte et consumimur igni")</lang>
wscript.echo isPalindrome( "In girum imus nocte et consumimur igni")</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 5,478: Line 5,478:
This routine checks if current line is a palindrome:
This routine checks if current line is a palindrome:


<lang vedit>:PALINDROME:
<syntaxhighlight lang="vedit">:PALINDROME:
EOL #2 = Cur_Col-2
EOL #2 = Cur_Col-2
BOL
BOL
Line 5,484: Line 5,484:
if (CC(#1) != CC(#2-#1)) { Return(0) }
if (CC(#1) != CC(#2-#1)) { Return(0) }
}
}
Return(1)</lang>
Return(1)</syntaxhighlight>


Testing:
Testing:


<lang vedit>Call("PALINDROME")
<syntaxhighlight lang="vedit">Call("PALINDROME")
if (Return_Value) {
if (Return_Value) {
Statline_Message("Yes")
Statline_Message("Yes")
Line 5,494: Line 5,494:
Statline_Message("No")
Statline_Message("No")
}
}
Return</lang>
Return</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|VBA}}
{{trans|VBA}}
<lang vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1


Function IsPalindrome(p As String) As Boolean
Function IsPalindrome(p As String) As Boolean
Line 5,509: Line 5,509:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>True</pre>
<pre>True</pre>


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang javascript>fn is_pal(ss string) bool {
<syntaxhighlight lang="javascript">fn is_pal(ss string) bool {
s := ss.runes()
s := ss.runes()
for i in 0..s.len/2 {
for i in 0..s.len/2 {
Line 5,528: Line 5,528:
println('$word => ${is_pal(word)}')
println('$word => ${is_pal(word)}')
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,542: Line 5,542:


=={{header|Wortel}}==
=={{header|Wortel}}==
<lang wortel>@let {
<syntaxhighlight lang="wortel">@let {
; Using a hook
; Using a hook
pal1 @(= @rev)
pal1 @(= @rev)
Line 5,554: Line 5,554:
!pal3 "In girum imus nocte et consumimur igni"
!pal3 "In girum imus nocte et consumimur igni"
]]
]]
}</lang>
}</syntaxhighlight>
Returns: <pre>[true false true]</pre>
Returns: <pre>[true false true]</pre>


=={{header|Wren}}==
=={{header|Wren}}==
<lang javascript>var isPal = Fn.new { |word| word == ((word.count > 0) ? word[-1..0] : "") }
<syntaxhighlight lang="javascript">var isPal = Fn.new { |word| word == ((word.count > 0) ? word[-1..0] : "") }


System.print("Are the following palindromes?")
System.print("Are the following palindromes?")
for (word in ["rotor", "rosetta", "step on no pets", "été", "wren", "🦊😀🦊"]) {
for (word in ["rotor", "rosetta", "step on no pets", "été", "wren", "🦊😀🦊"]) {
System.print(" %(word) => %(isPal.call(word))")
System.print(" %(word) => %(isPal.call(word))")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,577: Line 5,577:


=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
<lang x86asm>
<syntaxhighlight lang="x86asm">
; x86_84 Linux nasm
; x86_84 Linux nasm
section .text
section .text
Line 5,613: Line 5,613:
mov rax, 1
mov rax, 1
ret
ret
</syntaxhighlight>
</lang>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
string 0; \use zero-terminated strings


Line 5,641: Line 5,641:
CrLf(0);
CrLf(0);
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 5,657: Line 5,657:
is_palindrome (by changing case and stripping non-alphabetical characters).
is_palindrome (by changing case and stripping non-alphabetical characters).


<lang yorick>func is_palindrome(str) {
<syntaxhighlight lang="yorick">func is_palindrome(str) {
s = strchar(str)(:-1);
s = strchar(str)(:-1);
return allof(s == s(::-1));
return allof(s == s(::-1));
Line 5,666: Line 5,666:
w = where(s >= 'a' & s <= 'z');
w = where(s >= 'a' & s <= 'z');
return strchar(s(w));
return strchar(s(w));
}</lang>
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn pali(text){
<syntaxhighlight lang="zkl">fcn pali(text){
if (text.len()<2) return(False);
if (text.len()<2) return(False);
text==text.reverse();
text==text.reverse();
}
}
fcn pali2(text){ pali((text - " \t\n.,").toLower()) } // or whatever punctuation is</lang>
fcn pali2(text){ pali((text - " \t\n.,").toLower()) } // or whatever punctuation is</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,682: Line 5,682:


=={{header|Zoea}}==
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: palindrome
program: palindrome
case: 1
case: 1
Line 5,699: Line 5,699:
input: abc
input: abc
output: false
output: false
</syntaxhighlight>
</lang>


=={{header|Zoea Visual}}==
=={{header|Zoea Visual}}==