Narcissist: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Wren)
m (→‎{{header|Phix}}: missing /, or type it in)
 
(15 intermediate revisions by 11 users not shown)
Line 20: Line 20:
Took code from [[Quine]], has to be in one line (could be done pretty printed, too, but not as simple).
Took code from [[Quine]], has to be in one line (could be done pretty printed, too, but not as simple).


<lang Ada>with Ada.Text_IO;procedure Self is Q:Character:='"';A:String:="with Ada.Text_IO;procedure Self is Q:Character:='';A:String:=;B:String:=A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last);C:String:=Ada.Text_IO.Get_Line;begin Ada.Text_IO.Put_Line(Boolean'Image(B=C));end Self;";B:String:=A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last);C:String:=Ada.Text_IO.Get_Line;begin Ada.Text_IO.Put_Line(Boolean'Image(B=C));end Self;</lang>
<syntaxhighlight lang="ada">with Ada.Text_IO;procedure Self is Q:Character:='"';A:String:="with Ada.Text_IO;procedure Self is Q:Character:='';A:String:=;B:String:=A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last);C:String:=Ada.Text_IO.Get_Line;begin Ada.Text_IO.Put_Line(Boolean'Image(B=C));end Self;";B:String:=A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last);C:String:=Ada.Text_IO.Get_Line;begin Ada.Text_IO.Put_Line(Boolean'Image(B=C));end Self;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 27: Line 27:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''}}
<lang algol68>STRINGs="STRINGs="";print(readstring=2*s[:9]+2*s[9:])";print(readstring=2*s[:9]+2*s[9:])</lang>
<syntaxhighlight lang="algol68">STRINGs="STRINGs="";print(readstring=2*s[:9]+2*s[9:])";print(readstring=2*s[:9]+2*s[9:])</syntaxhighlight>
Output: T or F depending on input.
Output: T or F depending on input.

=={{header|AppleScript}}==

As long as the script hasn't been exported as run-only (''ie.'' without its source code):

<syntaxhighlight lang="applescript">(display dialog "" default answer "")'s text returned = (do shell script ("osadecompile " & (path to me)'s POSIX path's quoted form))</syntaxhighlight>

{{output}}
Depending on the text entered and button clicked, one of:
<syntaxhighlight lang="applescript">true
false
error "User cancelled." number -128</syntaxhighlight>

=={{header|Arturo}}==
<syntaxhighlight lang="arturo">blk:[print (("blk:" ++ (as .code blk) ++ "do blk") = input "") ? -> "accept" -> "reject"]do blk</syntaxhighlight>

{{out}}

<pre>$ arturo narcissist.art < narcissist.art
accept</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{works with|AutoHotkey 1.1}}
{{works with|AutoHotkey 1.1}}
<lang AutoHotkey>Narcissist(Input) {
<syntaxhighlight lang="autohotkey">Narcissist(Input) {
FileRead, Source, % A_ScriptFullPath
FileRead, Source, % A_ScriptFullPath
return Input == Source ? "accept" : "reject"
return Input == Source ? "accept" : "reject"
}</lang>
}</syntaxhighlight>
'''Example Use:'''
'''Example Use:'''
<lang AutoHotkey>MsgBox, % Narcissist(FileOpen(A_ScriptFullPath, "r").Read()) "`n"
<syntaxhighlight lang="autohotkey">MsgBox, % Narcissist(FileOpen(A_ScriptFullPath, "r").Read()) "`n"
. Narcissist("This isn't the text you're looking for.")</lang>
. Narcissist("This isn't the text you're looking for.")</syntaxhighlight>
{{Output}}
{{Output}}
<pre>accept
<pre>accept
Line 46: Line 66:
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
Prints '1' on success and '0' on failure.
Prints '1' on success and '0' on failure.
<lang bbcbasic>INPUT a$:PRINT -(a$=$(PAGE+34)+$(PAGE+33)):REM INPUT a$:PRINT -(a$=$(PAGE+34)+$(PAGE+33)):REM</lang>
<syntaxhighlight lang="bbcbasic">INPUT a$:PRINT -(a$=$(PAGE+34)+$(PAGE+33)):REM INPUT a$:PRINT -(a$=$(PAGE+34)+$(PAGE+33)):REM</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
Line 53: Line 73:
Outputs <tt>1</tt> if the given line of input matches the source code, and <tt>0</tt> if it doesn't.
Outputs <tt>1</tt> if the given line of input matches the source code, and <tt>0</tt> if it doesn't.


<lang befunge>900:0g~>:::0>`#0\#:5#:5#:+#<#~-#g*#0\#:5#+8#1+#\-#!*#-_$$"E"-!>_9-!.@</lang>
<syntaxhighlight lang="befunge">900:0g~>:::0>`#0\#:5#:5#:+#<#~-#g*#0\#:5#+8#1+#\-#!*#-_$$"E"-!>_9-!.@</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
Based upon the quine. Reads until EOF or newline from stdin, and writes "1" or "0" to stdout.
Based upon the quine. Reads until EOF or newline from stdin, and writes "1" or "0" to stdout.
<lang c>extern void*stdin;main(){ char*p = "extern void*stdin;main(){ char*p = %c%s%c,a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }",a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }</lang>
<syntaxhighlight lang="c">extern void*stdin;main(){ char*p = "extern void*stdin;main(){ char*p = %c%s%c,a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }",a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.IO;
using System.IO;
Line 89: Line 109:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Only checks the first line of stdin:
Only checks the first line of stdin:
<lang lisp>#1=(PRINT (EQUAL (WRITE-TO-STRING '#1# :CIRCLE 1) (READ-LINE *STANDARD-INPUT*)))</lang>
<syntaxhighlight lang="lisp">#1=(PRINT (EQUAL (WRITE-TO-STRING '#1# :CIRCLE 1) (READ-LINE *STANDARD-INPUT*)))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang D>import std.file; import std.stdio; import std.string; void main() { auto source = readText("narcissist.d").chomp; auto input = readln().chomp(); if (source == input) writeln("accept"); else writeln("reject"); }</lang>
<syntaxhighlight lang="d">import std.file; import std.stdio; import std.string; void main() { auto source = readText("narcissist.d").chomp; auto input = readln().chomp(); if (source == input) writeln("accept"); else writeln("reject"); }</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>!. = !prompt "Enter my code: " concat( swap !decode!utf-8 !encode!quoted dup swap ) "!. = !prompt \qEnter my code: \q concat( swap !decode!utf-8 !encode!quoted dup swap ) "</lang>
<syntaxhighlight lang="dejavu">!. = !prompt "Enter my code: " concat( swap !decode!utf-8 !encode!quoted dup swap ) "!. = !prompt \qEnter my code: \q concat( swap !decode!utf-8 !encode!quoted dup swap ) "</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==


<lang forth>: narcissist [ source ] sliteral compare 0= ;</lang>
<syntaxhighlight lang="forth">: narcissist [ source ] sliteral compare 0= ;</syntaxhighlight>


=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Dim As String a, s = "Dim As String a, s = Input a : Print (a = Left(s, 21) + Chr(34) + s + Chr(34) + Mid(s, 47, 3) + Mid(s, 23, 108)) + Mid(s, 54, 3)" : Input a : Print (a = Left(s, 21) + Chr(34) + s + Chr(34) + Mid(s, 47, 3) + Mid(s, 23, 108))</syntaxhighlight>



=={{header|Go}}==
=={{header|Go}}==
Line 109: Line 134:
This version reads until EOF and expects a newline at the end of the input. If this is being checked from a file, make sure that the file has exactly one newline at the end of it.
This version reads until EOF and expects a newline at the end of the input. If this is being checked from a file, make sure that the file has exactly one newline at the end of it.


<lang go>package main; import "os"; import "fmt"; import "bytes"; import "io/ioutil"; func main() {ios := "os"; ifmt := "fmt"; ibytes := "bytes"; iioutil := "io/ioutil"; zero := "Reject"; one := "Accept"; x := "package main; import %q; import %q; import %q; import %q; func main() {ios := %q; ifmt := %q; ibytes := %q; iioutil := %q; zero := %q; one := %q; x := %q; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}\n"; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}</lang>
<syntaxhighlight lang="go">package main; import "os"; import "fmt"; import "bytes"; import "io/ioutil"; func main() {ios := "os"; ifmt := "fmt"; ibytes := "bytes"; iioutil := "io/ioutil"; zero := "Reject"; one := "Accept"; x := "package main; import %q; import %q; import %q; import %q; func main() {ios := %q; ifmt := %q; ibytes := %q; iioutil := %q; zero := %q; one := %q; x := %q; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}\n"; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}</syntaxhighlight>
A version respecting the 80 character line limit:
A version respecting the 80 character line limit:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 149: Line 174:
}
}


var x = `</lang>
var x = `</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "</lang>
<syntaxhighlight lang="haskell">main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "</syntaxhighlight>


=={{header|Huginn}}==
=={{header|Huginn}}==
<lang huginn>#! /bin/sh
<syntaxhighlight lang="huginn">#! /bin/sh
exec huginn --no-argv -E "${0}"
exec huginn --no-argv -E "${0}"
#! huginn
#! huginn
Line 182: Line 207:
print( s == self ? "1\n" : "0\n" );
print( s == self ? "1\n" : "0\n" );
}
}
</syntaxhighlight>
</lang>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
{{trans|Go}}
{{trans|Go}}
Since we can't put a link statement and program on a single line, we implement a simplified inline sprintf so we don't have to deal with all the double quotes or substrings and offsets. If we'd needed to write multiple procedures on a line it can be done [[Icon%2BUnicon/Intro#Semi-colons| Semi-colons in the language intro]]
Since we can't put a link statement and program on a single line, we implement a simplified inline sprintf so we don't have to deal with all the double quotes or substrings and offsets. If we'd needed to write multiple procedures on a line it can be done [[Icon%2BUnicon/Intro#Semi-colons| Semi-colons in the language intro]]
<lang Icon>procedure main();yes:="Accept";no:="Reject";pat:="procedure main();yes:=$;no:=$;pat:=$;a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end";a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end</lang>
<syntaxhighlight lang="icon">procedure main();yes:="Accept";no:="Reject";pat:="procedure main();yes:=$;no:=$;pat:=$;a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end";a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end</syntaxhighlight>
Example:<pre>./narcissist.exe < narcissist.icn
Example:<pre>./narcissist.exe < narcissist.icn
Accept</pre>
Accept</pre>
Line 193: Line 218:


=={{header|J}}==
=={{header|J}}==
<lang j>#!/j602/bin/jconsole
<syntaxhighlight lang="j">#!/usr/bin/ijconsole
main=:3 : 0
main=:3 : 0 NB. tested under j602
self=: '#!/j602/bin/jconsole',LF,'main=:',(5!:5<'main'),LF,'main''''',LF
self=: '#!/j602/bin/jconsole',LF,'main=:',(5!:5<'main'),LF,'main''''',LF
echo self -: stdin''
echo self -: stdin''
)
)
main''</lang>
main''</syntaxhighlight>


Example use:
Example use:


<lang>$ ./narcissist.ijs <narcissist.ijs
<syntaxhighlight lang="text">$ ./narcissist.ijs <narcissist.ijs
1
1
</lang>
</syntaxhighlight>


Note that this assumes a suitable os command line.
Note that this assumes a suitable os command line.
Line 210: Line 235:


'''Alternative solution:'''
'''Alternative solution:'''
<lang j> narcissist=.(-:,~,2#{:)&'(-:,~,2#{:)&'''</lang>
<syntaxhighlight lang="j"> narcissist=.(-:,~,2#{:)&'(-:,~,2#{:)&'''</syntaxhighlight>


'''Example use:'''
'''Example use:'''
<lang j> (-:,~,2#{:)&'(-:,~,2#{:)&''' '(-:,~,2#{:)'
<syntaxhighlight lang="j"> (-:,~,2#{:)&'(-:,~,2#{:)&''' '(-:,~,2#{:)'
0
0
(-:,~,2#{:)&'(-:,~,2#{:)&''' '(-:,~,2#{:)&''(-:,~,2#{:)&'''''''
(-:,~,2#{:)&'(-:,~,2#{:)&''' '(-:,~,2#{:)&''(-:,~,2#{:)&'''''''
1</lang>
1</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.io.BufferedReader;
<syntaxhighlight lang="java">import java.io.BufferedReader;
import java.io.IOException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InputStreamReader;
Line 245: Line 270:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{works with|SpiderMonkey|1.7.0}}
{{works with|SpiderMonkey|1.7.0}}
Based upon [[Quine#Using_eval|one of the quines]]. Outputs 'true' if source is equal to inputted line (newline terminated), 'false' otherwise.
Based upon [[Quine#Using_eval|one of the quines]]. Outputs 'true' if source is equal to inputted line (newline terminated), 'false' otherwise.
<lang javascript>var code='var q=String.fromCharCode(39);print("var code=" + q + code + q + "; eval(code)" == readline())'; eval(code)</lang>
<syntaxhighlight lang="javascript">var code='var q=String.fromCharCode(39);print("var code=" + q + code + q + "; eval(code)" == readline())'; eval(code)</syntaxhighlight>


{{works with|JScript}}
{{works with|JScript}}
<lang javascript>var oFSO = new ActiveXObject("Scripting.FileSystemObject");
<syntaxhighlight lang="javascript">var oFSO = new ActiveXObject("Scripting.FileSystemObject");
function readfile(fname) {
function readfile(fname) {
var h = oFSO.OpenTextFile(fname, 1, false);
var h = oFSO.OpenTextFile(fname, 1, false);
Line 273: Line 298:
// compare and contrast
// compare and contrast
WScript.Echo(self === whatever ? "Accept" : "Reject");
WScript.Echo(self === whatever ? "Accept" : "Reject");
</syntaxhighlight>
</lang>


{{works with|Julia|1.2}}
{{works with|Julia|1.2}}


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>mysource = Base.read(Base.source_path(), String)
<syntaxhighlight lang="julia">mysource = Base.read(Base.source_path(), String)
println(Int(ARGS[1] == mysource))</lang>
println(Int(ARGS[1] == mysource))</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.0 (run on Windows 10)
<syntaxhighlight lang="scala">// version 1.1.0 (run on Windows 10)


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 290: Line 315:
val lines = Array<String>(n) { readLine()!! }
val lines = Array<String>(n) { readLine()!! }
if (lines.joinToString("\r\n") == text) println("\naccept") else println("\nreject")
if (lines.joinToString("\r\n") == text) println("\naccept") else println("\nreject")
}</lang>
}</syntaxhighlight>
First run (pasting in program text):
First run (pasting in program text):
{{out}}
{{out}}
Line 324: Line 349:
NOTE: You have to manually type in ALL of the code since the Input statement will not successfully input data from a paste event even though it will show up in the MainWin.
NOTE: You have to manually type in ALL of the code since the Input statement will not successfully input data from a paste event even though it will show up in the MainWin.


<syntaxhighlight lang="lb">
<lang lb>
s$ = "s$ = Input a$ : Print (a$ = Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 14, 3) + Mid$(s$, 6, 100)) + Mid$(s$, 23, 3)" : Input a$ : Print (a$ = Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 14, 3) + Mid$(s$, 6, 100))
s$ = "s$ = Input a$ : Print (a$ = Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 14, 3) + Mid$(s$, 6, 100)) + Mid$(s$, 23, 3)" : Input a$ : Print (a$ = Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 14, 3) + Mid$(s$, 6, 100))
</lang>
</syntaxhighlight>


=={{header|Mathematica}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
{{in}}
{{in}}
<lang Mathematica>prog = "prog = ``;\nPrint[InputString[] == \n ToString[StringForm[prog, ToString[prog, InputForm]]]];";
<syntaxhighlight lang="mathematica">prog = "prog = ``;\nPrint[InputString[] == \n ToString[StringForm[prog, ToString[prog, InputForm]]]];";
Print[InputString[] ==
Print[InputString[] == ToString[StringForm[prog, ToString[prog, InputForm]]]];</syntaxhighlight>
ToString[StringForm[prog, ToString[prog, InputForm]]]];</lang>
{{out}}
{{out}}
<pre>True</pre>
<pre>True</pre>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>import Nanoquery.IO
<syntaxhighlight lang="nanoquery">import Nanoquery.IO


// get a file tied to this program's source
// get a file tied to this program's source
Line 361: Line 385:


// if we got here, the lines are the same
// if we got here, the lines are the same
println "Accept"</lang>
println "Accept"</syntaxhighlight>

=={{header|Nim}}==
Program written on a single line to avoid problems with indentation. But we wanted to avoid the too easy solution consisting to read the source file. Input should be terminated by an end of file (Ctrl-D on Linux).
<syntaxhighlight lang="nim">
import strutils; let a = "import strutils; let a = $#; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))"; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))
</syntaxhighlight>

{{out}}
<pre>./narcissist
whatever...
0</pre>
<pre>
./narcissist <narcissist.nim
1</pre>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>narcissist()=input()==narcissist</lang>
<syntaxhighlight lang="parigp">narcissist()=input()==narcissist</syntaxhighlight>
Run narcissist():<pre>Hello
Run narcissist():<pre>Hello
0</pre>
0</pre>
Line 371: Line 409:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl># this is file narc.pl
<syntaxhighlight lang="perl"># this is file narc.pl
local $/;
local $/;
print do { open 0; <0> } eq <> ? "accept" : "reject";</lang>
print do { open 0; <0> } eq <> ? "accept" : "reject";</syntaxhighlight>
Run:
Run:
<lang>perl narc.pl < narc.pl</lang>
<syntaxhighlight lang="text">perl narc.pl < narc.pl</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--(notonline)-->
<lang Phix>puts(1,{"\n\ntrue\n\n","\n\nfalse\n\n"}[1+(gets(open(command_line()[2],"r"))!=gets(0))])</lang>
<syntaxhighlight lang="phix">
printf(1,"\n\n%t\n\n",get_text(command_line()[2],GT_LF_LAST)[1]=gets(0))
</syntaxhighlight>
{{out}}
Can be run using <code>p test.exw < test.exw</code> or the input manually typed in
<pre>
true
</pre>
<small>Aside: I suppose there should really be a leading <code>without js -- file i/o</code>, but I wanted to keep it a 1-liner.<br>
Interpreted-only, as is: to allow a compiled version to run, change <code>command_line()[2]</code> to (say) <code>"test.exw"</code><br>
or maybe <code>substitute(command_line()[2],".exe",".exw")</code>, and ship with/install the source code file.</small>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de narcissist (Str)
<syntaxhighlight lang="picolisp">(de narcissist (Str)
(= Str (str narcissist)) )</lang>
(= Str (str narcissist)) )</syntaxhighlight>
Output:
Output:
<pre>: (narcissist "(Str) (= Str (str narcissist))")
<pre>: (narcissist "(Str) (= Str (str narcissist))")
Line 389: Line 438:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Narcissist
function Narcissist
{
{
Line 396: Line 445:
Else { 'Reject' }
Else { 'Reject' }
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Narcissist 'Banana'
Narcissist 'Banana'
Line 407: Line 456:


'@
'@
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 416: Line 465:
=={{header|Python}}==
=={{header|Python}}==
{{Works with|Python|2}}
{{Works with|Python|2}}
<syntaxhighlight lang="python">
<lang Python>
import sys
import sys
with open(sys.argv[0]) as quine:
with open(sys.argv[0]) as quine:
Line 424: Line 473:
else:
else:
print("Reject")
print("Reject")
</syntaxhighlight>
</lang>


{{Works with|Python|3}}
{{Works with|Python|3}}
<syntaxhighlight lang="python">
<lang Python>
_='_=%r;print (_%%_==input())';print (_%_==input())
_='_=%r;print (_%%_==input())';print (_%_==input())
</syntaxhighlight>
</lang>

=={{header|Quackery}}==

As a dialogue in the Quackery shell. (REPL)

<syntaxhighlight lang="quackery">Welcome to Quackery.

Enter "leave" to leave the shell.

/O> [ this copy unbuild = ] is narcissist
... $ "[ this copy unbuild = ]" narcissist
...

Stack: 1

/O> drop
... $ "Nothing is more important than my egomania. -- Clara Oswald" narcissist
...

Stack: 0

/O> leave
...

Cheerio.</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 436: Line 510:
typed when the code stops to read some input.
typed when the code stops to read some input.


<syntaxhighlight lang="racket">
<lang Racket>
-> ((lambda (x) (equal? (read) (list x (list 'quote x))))
-> ((lambda (x) (equal? (read) (list x (list 'quote x))))
'(lambda (x) (equal? (read) (list x (list 'quote x)))))
'(lambda (x) (equal? (read) (list x (list 'quote x)))))
Line 442: Line 516:
'(lambda (x) (equal? (read) (list x (list 'quote x)))))
'(lambda (x) (equal? (read) (list x (list 'quote x)))))
#t
#t
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 451: Line 525:
Note how the code takes advantage of Raku's ability to nest quoting delimiters.
Note how the code takes advantage of Raku's ability to nest quoting delimiters.


<lang perl6>EVAL my $self = q{say slurp() eq q[EVAL my $self = q{]~$self~q[}]~10.chr ?? q{Beautiful!} !! q{Not my type.}}</lang>
<syntaxhighlight lang="raku" line>EVAL my $self = q{say slurp() eq q[EVAL my $self = q{]~$self~q[}]~10.chr ?? q{Beautiful!} !! q{Not my type.}}</syntaxhighlight>


{{out}}
{{out}}
Line 464: Line 538:
===version 1===
===version 1===
(returns &nbsp; '''1''' &nbsp; or &nbsp; '''0''')
(returns &nbsp; '''1''' &nbsp; or &nbsp; '''0''')
<lang rexx>/*REXX*/ say arg(1)=sourceline(1)</lang>
<syntaxhighlight lang="rexx">/*REXX*/ say arg(1)=sourceline(1)</syntaxhighlight>


===version 2===
===version 2===
(returns &nbsp; '''accept''' &nbsp; or &nbsp; '''reject''')
(returns &nbsp; '''accept''' &nbsp; or &nbsp; '''reject''')
<lang rexx>/*REXX*/ say word('reject accept',1+(arg(1)=sourceline(1)))</lang>
<syntaxhighlight lang="rexx">/*REXX*/ say word('reject accept',1+(arg(1)=sourceline(1)))</syntaxhighlight>

≪ ‘NAR6’ RCL == ≫
‘NAR6’ STO
{{in}}
<pre>
≪ ‘NAR6’ RCL == ≫ NAR6
</pre>
{{out}}
<pre>
1: 1
</pre>
=={{header|RPL}}==
« LASTARG RCL →STR == » '<span style="color:blue">NARCISSIST</span>' STO


"« LASTARG RCL →STR == »" '<span style="color:blue">NARCISSIST</span>' EVAL <span style="color:grey">@ returns 1</span>
"string" '<span style="color:blue">NARCISSIST</span>' EVAL <span style="color:grey">@ returns 0</span>
=={{header|Ruby}}==
=={{header|Ruby}}==
Translation of the C version.
Translation of the C version.
<lang ruby>s = "s = %s%s%s; puts(gets.chomp == (s %% [34.chr, s, 34.chr]) ? 'accept' : 'reject')"; puts(gets.chomp == (s % [34.chr, s, 34.chr]) ? 'accept' : 'reject')</lang>
<syntaxhighlight lang="ruby">s = "s = %s%s%s; puts(gets.chomp == (s %% [34.chr, s, 34.chr]) ? 'accept' : 'reject')"; puts(gets.chomp == (s % [34.chr, s, 34.chr]) ? 'accept' : 'reject')</syntaxhighlight>
Output:
Output:
<pre>$ ruby narcissist.rb < narcissist.rb
<pre>$ ruby narcissist.rb < narcissist.rb
Line 478: Line 567:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::io::{stdin, prelude::*};
<syntaxhighlight lang="rust">use std::io::{stdin, prelude::*};
fn main() {
fn main() {
let src = include_str!("main.rs");
let src = include_str!("main.rs");
Line 487: Line 576:
.expect("Could not read from STDIN");
.expect("Could not read from STDIN");
println!("{}", src == input);
println!("{}", src == input);
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>import scala.io.StdIn
<syntaxhighlight lang="scala">import scala.io.StdIn


object Narcissist extends App {
object Narcissist extends App {
Line 500: Line 589:
}
}
if (lines.mkString("\r\n") == text) println("\naccept") else println("\nreject")
if (lines.mkString("\r\n") == text) println("\naccept") else println("\nreject")
}</lang>
}</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>say (File.new(__FILE__).open_r.slurp == ARGF.slurp);</lang>
<syntaxhighlight lang="ruby">say (File.new(__FILE__).open_r.slurp == ARGF.slurp);</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>#! /usr/bin/swift
<syntaxhighlight lang="swift">#! /usr/bin/swift
import Foundation
import Foundation


Line 519: Line 608:
} else {
} else {
print("Reject")
print("Reject")
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
With the use of explicit reflexive introspection:
With the use of explicit reflexive introspection:
<lang tcl>apply {{} {puts [expr {[gets stdin] eq [info level 0]}]}}</lang>
<syntaxhighlight lang="tcl">apply {{} {puts [expr {[gets stdin] eq [info level 0]}]}}</syntaxhighlight>
Without such commands, using pure generation of strings and lists:
Without such commands, using pure generation of strings and lists:
<lang tcl>apply {s {puts [expr {[gets stdin]eq[list {*}$s $s]}]}} {apply {s {puts [expr {[gets stdin]eq[list {*}$s $s]}]}}}</lang>
<syntaxhighlight lang="tcl">apply {s {puts [expr {[gets stdin]eq[list {*}$s $s]}]}} {apply {s {puts [expr {[gets stdin]eq[list {*}$s $s]}]}}}</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==


<lang txr>@(bind my64 "QChuZXh0IDphcmdzKUBmaWxlbmFtZUAobmV4dCBmaWxlbmFtZSlAZmlyc3RsaW5lQChmcmVlZm9ybSAiIilAcmVzdEAoYmluZCBpbjY0IEAoYmFzZTY0LWVuY29kZSByZXN0KSlAKGNhc2VzKUAgIChiaW5kIGZpcnN0bGluZSBgXEAoYmluZCBteTY0ICJAbXk2NCIpYClAICAoYmluZCBpbjY0IG15NjQpQCAgKGJpbmQgcmVzdWx0ICIxIilAKG9yKUAgIChiaW5kIHJlc3VsdCAiMCIpQChlbmQpQChvdXRwdXQpQHJlc3VsdEAoZW5kKQ==")
<syntaxhighlight lang="txr">@(bind my64 "QChuZXh0IDphcmdzKUBmaWxlbmFtZUAobmV4dCBmaWxlbmFtZSlAZmlyc3RsaW5lQChmcmVlZm9ybSAiIilAcmVzdEAoYmluZCBpbjY0IEAoYmFzZTY0LWVuY29kZSByZXN0KSlAKGNhc2VzKUAgIChiaW5kIGZpcnN0bGluZSBgXEAoYmluZCBteTY0ICJAbXk2NCIpYClAICAoYmluZCBpbjY0IG15NjQpQCAgKGJpbmQgcmVzdWx0ICIxIilAKG9yKUAgIChiaW5kIHJlc3VsdCAiMCIpQChlbmQpQChvdXRwdXQpQHJlc3VsdEAoZW5kKQ==")
@(next :args)
@(next :args)
@filename
@filename
Line 547: Line 636:
@result
@result
@(end)
@(end)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 555: Line 644:


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>cmp "$0" >/dev/null && echo accept || echo reject</lang>
<syntaxhighlight lang="bash">cmp "$0" >/dev/null && echo accept || echo reject</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
Based on the quine
Based on the quine
<lang vb>Public Sub narcissist()
<syntaxhighlight lang="vb">Public Sub narcissist()
quote = Chr(34)
quote = Chr(34)
comma = Chr(44)
comma = Chr(44)
Line 600: Line 689:
Next i
Next i
Debug.Print IIf(flag, 1, 0)
Debug.Print IIf(flag, 1, 0)
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "os" for Process, Platform
<syntaxhighlight lang="wren">import "os" for Process, Platform
import "io" for File, Stdin, Stdout
import "io" for File, Stdin, Stdout


Line 622: Line 711:
} else {
} else {
System.print("reject")
System.print("reject")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 637: Line 726:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>stdin:=File.stdin.read();
<syntaxhighlight lang="zkl">stdin:=File.stdin.read();
thisFileSrc:=File(System.argv[1]).read();
thisFileSrc:=File(System.argv[1]).read();
println((stdin==thisFileSrc) and "input matches "+System.argv[1] or "No match");</lang>
println((stdin==thisFileSrc) and "input matches "+System.argv[1] or "No match");</syntaxhighlight>
Since zkl is [usually] compile-when-run, we just compare the contents of source file to stdin.
Since zkl is [usually] compile-when-run, we just compare the contents of source file to stdin.
{{out}}
{{out}}

Latest revision as of 13:43, 13 January 2024

Task
Narcissist
You are encouraged to solve this task according to the task description, using any language you may know.

Quoting from the Esolangs wiki page:

A narcissist (or Narcissus program) is the decision-problem version of a quine.

A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.

For concreteness, in this task we shall assume that symbol = character.

The narcissist should be able to cope with any finite input, whatever its length.

Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.

Ada

Works with: Ada 2005

Took code from Quine, has to be in one line (could be done pretty printed, too, but not as simple).

with Ada.Text_IO;procedure Self is Q:Character:='"';A:String:="with Ada.Text_IO;procedure Self is Q:Character:='';A:String:=;B:String:=A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last);C:String:=Ada.Text_IO.Get_Line;begin Ada.Text_IO.Put_Line(Boolean'Image(B=C));end Self;";B:String:=A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last);C:String:=Ada.Text_IO.Get_Line;begin Ada.Text_IO.Put_Line(Boolean'Image(B=C));end Self;

ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
STRINGs="STRINGs="";print(readstring=2*s[:9]+2*s[9:])";print(readstring=2*s[:9]+2*s[9:])

Output: T or F depending on input.

AppleScript

As long as the script hasn't been exported as run-only (ie. without its source code):

(display dialog "" default answer "")'s text returned = (do shell script ("osadecompile " & (path to me)'s POSIX path's quoted form))
Output:

Depending on the text entered and button clicked, one of:

true
false
error "User cancelled." number -128

Arturo

blk:[print (("blk:" ++ (as .code blk) ++ "do blk") = input "") ? -> "accept" -> "reject"]do blk
Output:
$ arturo narcissist.art < narcissist.art
accept

AutoHotkey

Works with: AutoHotkey 1.1
Narcissist(Input) {
	FileRead, Source, % A_ScriptFullPath
	return Input == Source ? "accept" : "reject"
}

Example Use:

MsgBox, % Narcissist(FileOpen(A_ScriptFullPath, "r").Read()) "`n"
	. Narcissist("This isn't the text you're looking for.")
Output:
accept
reject

BBC BASIC

Prints '1' on success and '0' on failure.

INPUT a$:PRINT -(a$=$(PAGE+34)+$(PAGE+33)):REM INPUT a$:PRINT -(a$=$(PAGE+34)+$(PAGE+33)):REM

Befunge

Reads from stdin up to the first carriage return, line feed, or EOF. However, the latter is not guaranteed to work on all Befunge implementations - in particular not on Befunge-98 - so a line break is recommended.

Outputs 1 if the given line of input matches the source code, and 0 if it doesn't.

900:0g~>:::0>`#0\#:5#:5#:+#<#~-#g*#0\#:5#+8#1+#\-#!*#-_$$"E"-!>_9-!.@

C

Based upon the quine. Reads until EOF or newline from stdin, and writes "1" or "0" to stdout.

extern void*stdin;main(){ char*p = "extern void*stdin;main(){ char*p = %c%s%c,a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }",a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }

C#

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Narcisisst
{
	class Program
	{
		public static void Main(string[] args)
		{
			const string path = @"E:\Narcisisst";
			string[] thisFile = Directory.GetFiles(path , "Program.cs");
			StringBuilder sb = new StringBuilder();
			
				foreach (string readLine in File.ReadLines(thisFile[0]))
				{
					sb.Append(readLine);
					sb.Append("\n");
				}
				
			Console.WriteLine(sb);
			string input =String.Empty;
			       	input = Console.ReadLine();
			       	Console.WriteLine((Regex.IsMatch(sb.ToString(),input))?"accept":"reject");
			       	Console.ReadKey();
			 }
	}
}

Common Lisp

Only checks the first line of stdin:

#1=(PRINT (EQUAL (WRITE-TO-STRING '#1# :CIRCLE 1) (READ-LINE *STANDARD-INPUT*)))

D

import std.file; import std.stdio; import std.string; void main() { auto source = readText("narcissist.d").chomp; auto input = readln().chomp(); if (source == input) writeln("accept"); else writeln("reject"); }

Déjà Vu

!. = !prompt "Enter my code: " concat( swap !decode!utf-8 !encode!quoted dup swap ) "!. = !prompt \qEnter my code: \q concat( swap !decode!utf-8 !encode!quoted dup swap ) "

Forth

: narcissist  [ source ] sliteral compare 0= ;


FreeBASIC

Dim As String a, s = "Dim As String a, s = Input a : Print (a = Left(s, 21) + Chr(34) + s + Chr(34) + Mid(s, 47, 3) + Mid(s, 23, 108)) + Mid(s, 54, 3)" : Input a : Print (a = Left(s, 21) + Chr(34) + s + Chr(34) + Mid(s, 47, 3) + Mid(s, 23, 108))


Go

This version reads until EOF and expects a newline at the end of the input. If this is being checked from a file, make sure that the file has exactly one newline at the end of it.

package main; import "os"; import "fmt"; import "bytes"; import "io/ioutil"; func main() {ios := "os"; ifmt := "fmt"; ibytes := "bytes"; iioutil := "io/ioutil"; zero := "Reject"; one := "Accept"; x := "package main; import %q; import %q; import %q; import %q; func main() {ios := %q; ifmt := %q; ibytes := %q; iioutil := %q; zero := %q; one := %q; x := %q; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}\n"; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}

A version respecting the 80 character line limit:

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    s := fmt.Sprintf("%s%c%s%c\n", x, 0x60, x, 0x60)
    in, _ := ioutil.ReadAll(os.Stdin)
    if bytes.Equal(in, []byte(s)) {
        fmt.Println("Accept")
    } else {
        fmt.Println("Reject")
    }
}

var x = `package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    s := fmt.Sprintf("%s%c%s%c\n", x, 0x60, x, 0x60)
    in, _ := ioutil.ReadAll(os.Stdin)
    if bytes.Equal(in, []byte(s)) {
        fmt.Println("Accept")
    } else {
        fmt.Println("Reject")
    }
}

var x = `

Haskell

main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "

Huginn

#! /bin/sh
exec huginn --no-argv -E "${0}"
#! huginn

main() {
	c = "#! /bin/sh{1}~"
		"exec huginn --no-argv -E {3}${{0}}{3}{1}#! huginn{1}{1}~"
		"main() {{{1}{2}c = {3}{0}{3};{1}~"
		"{2}s = {3}{3};{1}~"
		"{2}while ( ( line = input() ) != none ) {{{1}~"
		"{2}{2}s += line;{1}~"
		"{2}}}{1}~"
		"{2}self = copy( c ).replace( {3}{5}{3}, {3}{3} )~"
		".format({1}{2}{2}c.replace( {3}{5}{3}, ~"
		"{3}{5}{4}{3}{4}n{4}t{4}t{4}{3}{3} ), ~"
		"{3}{4}n{3}, {3}{4}t{3}, {3}{4}{3}{3}, {3}{4}{4}{3}, ~"
		"{3}{5}{3}{1}{2});{1}~"
		"{2}print( s == self ? {3}1{4}n{3} : {3}0{4}n{3} );{1}}}{1}{1}";
	s = "";
	while ( ( line = input() ) != none ) {
		s += line;
	}
	self = copy( c ).replace( "~", "" ).format(
		c.replace( "~", "~\"\n\t\t\"" ), "\n", "\t", "\"", "\\", "~"
	);
	print( s == self ? "1\n" : "0\n" );
}

Icon and Unicon

Translation of: Go

Since we can't put a link statement and program on a single line, we implement a simplified inline sprintf so we don't have to deal with all the double quotes or substrings and offsets. If we'd needed to write multiple procedures on a line it can be done Semi-colons in the language intro

procedure main();yes:="Accept";no:="Reject";pat:="procedure main();yes:=$;no:=$;pat:=$;a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end";a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end

Example:

./narcissist.exe < narcissist.icn
Accept

Actually, this version recognizes all files where the first line is the Narcissist.

J

#!/usr/bin/ijconsole
main=:3 : 0  NB. tested under j602
  self=: '#!/j602/bin/jconsole',LF,'main=:',(5!:5<'main'),LF,'main''''',LF
  echo  self -: stdin''
)
main''

Example use:

$ ./narcissist.ijs <narcissist.ijs
1

Note that this assumes a suitable os command line.


Alternative solution:

   narcissist=.(-:,~,2#{:)&'(-:,~,2#{:)&'''

Example use:

   (-:,~,2#{:)&'(-:,~,2#{:)&''' '(-:,~,2#{:)'
0
   (-:,~,2#{:)&'(-:,~,2#{:)&''' '(-:,~,2#{:)&''(-:,~,2#{:)&'''''''
1

Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Narcissist {
    private static final String SOURCE = "import java.io.BufferedReader;%nimport java.io.IOException;%nimport java.io.InputStreamReader;%n%npublic class Narcissist {%n    private static final String SOURCE = %c%s%c;%n    private static final char QUOTE = 0x22;%n%n    public static void main(String[] args) throws IOException {%n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));%n        StringBuilder sb = new StringBuilder();%n%n        while (true) {%n            String line = br.readLine();%n            if (null == line) break;%n            sb.append(line).append(System.lineSeparator());%n        }%n%n        String program = String.format(SOURCE, QUOTE, SOURCE, QUOTE, QUOTE, QUOTE, QUOTE, QUOTE);%n        if (program.equals(sb.toString())) {%n            System.out.println(%caccept%c);%n        } else {%n            System.out.println(%creject%c);%n        }%n    }%n}%n";
    private static final char QUOTE = 0x22;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        while (true) {
            String line = br.readLine();
            if (null == line) break;
            sb.append(line).append(System.lineSeparator());
        }

        String program = String.format(SOURCE, QUOTE, SOURCE, QUOTE, QUOTE, QUOTE, QUOTE, QUOTE);
        if (program.equals(sb.toString())) {
            System.out.println("accept");
        } else {
            System.out.println("reject");
        }
    }
}

JavaScript

Works with: SpiderMonkey version 1.7.0

Based upon one of the quines. Outputs 'true' if source is equal to inputted line (newline terminated), 'false' otherwise.

var code='var q=String.fromCharCode(39);print("var code=" + q + code + q + "; eval(code)" == readline())'; eval(code)
Works with: JScript
var oFSO = new ActiveXObject("Scripting.FileSystemObject");
function readfile(fname) {
	var h = oFSO.OpenTextFile(fname, 1, false);
	var result = h.ReadAll();
	h.Close();
	return result;
}

if (0 === WScript.Arguments.UnNamed.Count) {
	WScript.Echo(WScript.ScriptName,"filename");
	WScript.Quit();
}

// first read self 
var self = readfile(WScript.ScriptFullName);
// read whatever file is given on commmand line
var whatever = readfile(WScript.Arguments.UnNamed(0));

// compare and contrast
WScript.Echo(self === whatever ? "Accept" : "Reject");
Works with: Julia version 1.2

Julia

mysource = Base.read(Base.source_path(), String)
println(Int(ARGS[1] == mysource))

Kotlin

// version 1.1.0 (run on Windows 10)

fun main(args: Array<String>) {
    val text = java.io.File("narcissist.kt").readText()
    println("Enter the number of lines to be input followed by those lines:\n")
    val n = readLine()!!.toInt()
    val lines = Array<String>(n) { readLine()!! }
    if (lines.joinToString("\r\n") == text) println("\naccept") else println("\nreject")
}

First run (pasting in program text):

Output:
Enter the number of lines to be input followed by those lines:

9
// version 1.1.0 (run on Windows 10)

fun main(args: Array<String>) {
    val text = java.io.File("narcissist.kt").readText()
    println("Enter the number of lines to be input followed by those lines:\n")
    val n = readLine()!!.toInt()
    val lines = Array<String>(n) { readLine()!! }
    if (lines.joinToString("\r\n") == text) println("\naccept") else println("\nreject")
}

accept

Second run (entering any old rubbish):

Output:
Enter the number of lines to be input followed by those lines:

1
the quick brown fox

reject

Liberty BASIC

NOTE: You have to manually type in ALL of the code since the Input statement will not successfully input data from a paste event even though it will show up in the MainWin.

 s$ = "s$ = Input a$ : Print (a$ = Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 14, 3) + Mid$(s$, 6, 100)) + Mid$(s$, 23, 3)" : Input a$ : Print (a$ = Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 14, 3) + Mid$(s$, 6, 100))

Mathematica/Wolfram Language

Input:
prog = "prog = ``;\nPrint[InputString[] == \n   ToString[StringForm[prog, ToString[prog, InputForm]]]];";
Print[InputString[] == ToString[StringForm[prog, ToString[prog, InputForm]]]];
Output:
True

Nanoquery

import Nanoquery.IO

// get a file tied to this program's source
$f = new(File, $args[len($args) - 1])

// get the source and split across lines
$source = split($f.readAll(), "\n")

// read that amount of lines from the console
$in = list(len($source))
for ($i = 0) ($i < len($source)) ($i = $i + 1)
	append $in input()
end

// check line by line
for ($i = 0) ($i < len($in)) ($i = $i + 1)
	// check if the lines are equal
	if ($in[$i] != $source[$i])
		println "Reject"
		exit
	end
end

// if we got here, the lines are the same
println "Accept"

Nim

Program written on a single line to avoid problems with indentation. But we wanted to avoid the too easy solution consisting to read the source file. Input should be terminated by an end of file (Ctrl-D on Linux).

import strutils; let a = "import strutils; let a = $#; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))"; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))
Output:
./narcissist
whatever...
0
./narcissist <narcissist.nim
1

PARI/GP

narcissist()=input()==narcissist

Run narcissist():

Hello
0
narcissist() = {input() == narcissist;}
1

Perl

# this is file narc.pl
local $/;
print do { open 0; <0> } eq <> ? "accept" : "reject";

Run:

perl narc.pl < narc.pl

Phix

printf(1,"\n\n%t\n\n",get_text(command_line()[2],GT_LF_LAST)[1]=gets(0))
Output:

Can be run using p test.exw < test.exw or the input manually typed in

true

Aside: I suppose there should really be a leading without js -- file i/o, but I wanted to keep it a 1-liner.
Interpreted-only, as is: to allow a compiled version to run, change command_line()[2] to (say) "test.exw"
or maybe substitute(command_line()[2],".exe",".exw"), and ship with/install the source code file.

PicoLisp

(de narcissist (Str)
   (= Str (str narcissist)) )

Output:

: (narcissist "(Str) (= Str (str narcissist))")
-> T

PowerShell

Works with: PowerShell version 2
function Narcissist
{
Param ( [string]$String )
If ( $String -eq $MyInvocation.MyCommand.Definition ) { 'Accept' }
Else { 'Reject' }
}
Narcissist 'Banana'
 
Narcissist @'

Param ( [string]$String )
If ( $String -eq $MyInvocation.MyCommand.Definition ) { 'Accept' }
Else { 'Reject' }

'@
Output:
Reject
Accept

Python

Works with: Python version 2
import sys
with open(sys.argv[0]) as quine:
    code = raw_input("Enter source code: ")
    if code == quine.read():
        print("Accept")
    else:
        print("Reject")
Works with: Python version 3
_='_=%r;print (_%%_==input())';print (_%_==input())

Quackery

As a dialogue in the Quackery shell. (REPL)

Welcome to Quackery.

Enter "leave" to leave the shell.

/O> [ this copy unbuild = ] is narcissist
... $ "[ this copy unbuild = ]" narcissist
... 

Stack: 1 

/O> drop
... $ "Nothing is more important than my egomania. -- Clara Oswald" narcissist
... 

Stack: 0 

/O> leave
... 

Cheerio.

Racket

This shows a REPL interaction, where the second expression is what is typed when the code stops to read some input.

-> ((lambda (x) (equal? (read) (list x (list 'quote x))))
   '(lambda (x) (equal? (read) (list x (list 'quote x)))))
((lambda (x) (equal? (read) (list x (list 'quote x))))
 '(lambda (x) (equal? (read) (list x (list 'quote x)))))
#t

Raku

(formerly Perl 6)

For the narcissist to work you must be very careful with whitespace. The following version works if it is given to standard input as exactly one line terminated by a newline character.

Note how the code takes advantage of Raku's ability to nest quoting delimiters.

EVAL my $self = q{say slurp() eq q[EVAL my $self = q{]~$self~q[}]~10.chr ?? q{Beautiful!} !! q{Not my type.}}
Output:
$ narcissist='EVAL my $self = q{say slurp() eq q[EVAL my $self = q{]~$self~q[}]~10.chr ?? q{Beautiful!} !! q{Not my type.}}'
$ raku -e "$narcissist" <<<"$narcissist"
Beautiful!
$ raku -e "$narcissist" <<<"$narcissist # a comment ruining it all" 
Not my type.

REXX

version 1

(returns   1   or   0)

/*REXX*/ say arg(1)=sourceline(1)

version 2

(returns   accept   or   reject)

/*REXX*/ say word('reject accept',1+(arg(1)=sourceline(1)))
≪ ‘NAR6’ RCL == ≫ 
‘NAR6’ STO
Input:
≪ ‘NAR6’ RCL == ≫ NAR6
Output:
1: 1

RPL

« LASTARG RCL →STR == » 'NARCISSIST' STO
"« LASTARG RCL →STR == »" 'NARCISSIST' EVAL     @ returns 1
"string" 'NARCISSIST' EVAL                      @ returns 0

Ruby

Translation of the C version.

s = "s = %s%s%s; puts(gets.chomp == (s %% [34.chr, s, 34.chr]) ? 'accept' : 'reject')"; puts(gets.chomp == (s % [34.chr, s, 34.chr]) ? 'accept' : 'reject')

Output:

$ ruby narcissist.rb < narcissist.rb
accept

Rust

use std::io::{stdin, prelude::*};
fn main() {
    let src = include_str!("main.rs");
    let mut input = String::new();
    stdin()
        .lock()
        .read_to_string(&mut input)
        .expect("Could not read from STDIN");
    println!("{}", src == input);
}

Scala

import scala.io.StdIn

object Narcissist extends App {
  val text = scala.io.Source.fromFile("Narcissist.scala", "UTF-8").toStream
  println("Enter the number of lines to be input followed by those lines:\n")
  val n = StdIn.readInt()
  val lines = Stream {
    StdIn.readLine()
  }
  if (lines.mkString("\r\n") == text) println("\naccept") else println("\nreject")
}

Sidef

say (File.new(__FILE__).open_r.slurp == ARGF.slurp);

Swift

#! /usr/bin/swift
import Foundation

let script = CommandLine.arguments[0]
print(script)
let mytext = try? String.init(contentsOfFile: script, encoding: .utf8)

var enteredtext = readLine()
if mytext == enteredtext {
    print("Accept")
} else {
    print("Reject")
}

Tcl

With the use of explicit reflexive introspection:

apply {{} {puts [expr {[gets stdin] eq [info level 0]}]}}

Without such commands, using pure generation of strings and lists:

apply {s {puts [expr {[gets stdin]eq[list {*}$s $s]}]}} {apply {s {puts [expr {[gets stdin]eq[list {*}$s $s]}]}}}

TXR

@(bind my64 "QChuZXh0IDphcmdzKUBmaWxlbmFtZUAobmV4dCBmaWxlbmFtZSlAZmlyc3RsaW5lQChmcmVlZm9ybSAiIilAcmVzdEAoYmluZCBpbjY0IEAoYmFzZTY0LWVuY29kZSByZXN0KSlAKGNhc2VzKUAgIChiaW5kIGZpcnN0bGluZSBgXEAoYmluZCBteTY0ICJAbXk2NCIpYClAICAoYmluZCBpbjY0IG15NjQpQCAgKGJpbmQgcmVzdWx0ICIxIilAKG9yKUAgIChiaW5kIHJlc3VsdCAiMCIpQChlbmQpQChvdXRwdXQpQHJlc3VsdEAoZW5kKQ==")
@(next :args)
@filename
@(next filename)
@firstline
@(freeform "")
@rest
@(bind in64 @(base64-encode rest))
@(cases)
@  (bind firstline `\@(bind my64 "@my64")`)
@  (bind in64 my64)
@  (bind result "1")
@(or)
@  (bind result "0")
@(end)
@(output)
@result
@(end)
Output:
$ txr narcissist.txr narcissist.txr
1

UNIX Shell

cmp "$0" >/dev/null && echo accept || echo reject

VBA

Based on the quine

Public Sub narcissist()
    quote = Chr(34)
    comma = Chr(44)
    cont = Chr(32) & Chr(95)
    rparen = Chr(41)
    n = Array( _
"Public Sub narcissist()", _
"    quote = Chr(34)", _
"    comma = Chr(44)", _
"    cont = Chr(32) & Chr(95)", _
"    rparen = Chr(41)", _
"    n = Array( _", _
"How many lines?", _
"Line ", _
"    x = InputBox(n(5))", _
"    flag = True", _
"    For i = 0 To 5", _
"        If InputBox(n(6) & i) <> n(i) Then flag = False", _
"    Next i", _
"    For i = 0 To 20", _
"        If InputBox(n(6) & i + 6) <> quote & n(i) & quote & comma & cont Then flag = False", _
"    Next i", _
"    If InputBox(n(6) & 27) <> quote & n(21) & quote & rparen Then flag = False", _
"    For i = 7 To 21", _
"        If InputBox(n(6) & i + 21) <> n(i) Then flag = False", _
"    Next i", _
"    Debug.Print IIf(flag, 1, 0)", _
"End Sub")
    x = InputBox(n(5))
    flag = True
    For i = 0 To 5
        If InputBox(n(6) & i) <> n(i) Then flag = False
    Next i
    For i = 0 To 20
        If InputBox(n(6) & i + 6) <> quote & n(i) & quote & comma & cont Then flag = False
    Next i
    If InputBox(n(6) & 27) <> quote & n(21) & quote & rparen Then flag = False
    For i = 7 To 21
        If InputBox(n(6) & i + 21) <> n(i) Then flag = False
    Next i
    Debug.Print IIf(flag, 1, 0)
End Sub

Wren

import "os" for Process, Platform
import "io" for File, Stdin, Stdout

var args = Process.allArguments
var text = File.read(args[1]).trim()
System.print("Enter the number of lines to be input followed by those lines:\n")
Stdout.flush()
var n = Num.fromString(Stdin.readLine())
var lines = List.filled(n, null)
for (i in 0...n) lines[i] = Stdin.readLine()
var joiner = Platform.isWindows ? "\r\n" : "\n"
var text2 = lines.join(joiner)
System.print()
if (text2 == text) {
    System.print("accept")
} else if (text.startsWith(text2)) {
    System.print("not yet finished")
} else {
    System.print("reject")
}
Output:

Sample session:

Enter the number of lines to be input followed by those lines:

2
import "os" for Process, Platform
import "io" for File, Stdin, Stdout

not yet finished

zkl

stdin:=File.stdin.read();
thisFileSrc:=File(System.argv[1]).read();
println((stdin==thisFileSrc) and "input matches "+System.argv[1] or "No match");

Since zkl is [usually] compile-when-run, we just compare the contents of source file to stdin.

Output:
$ zkl narcissist.zkl <narcissist.zkl 
input matches narcissist.zkl
$ zkl narcissist.zkl <narcissist3.zkl 
No match