Skip to main content

自產生程式

自產生程式是很有趣的程式,以美國哲學家、邏輯學家威拉德.奎因(Willard Quine)命名,專指一段程式運行時,會輸出與程式碼本身一樣的結果。 有一個特殊要求是,該段程式碼必須不讀寫檔案也能做到,所以以下的Bash 程式碼不是Quine。

#!/bin/bash
# You cannot read the file from hard disk
cat $0

JavaScript例子

有不少例子都可以做到自產生程式的效果,以下是一段我寫的JavaScript,就是一個很直接的Quine。

const quote = String.fromCharCode(96);
const codes = `const quote = String.fromCharCode(96);
const codes = {};
console.log(codes.replace("{}",quote+codes+quote));
`;
console.log(codes.replace("{}",quote+codes+quote));

箇中關鍵是因為在引號裏面不可以再放引號,因此要用String.fromCharCode(96)去做出一個雙引號,然後最後一行的

console.log(codes.replace("{}",quote+codes+quote));

取代為原本的句子。

Python例子

Python例子縱使有更短的例子,以下是一段與上面JavaScript思路相同的程式碼。

codes = """codes = []
print(codes.replace("[]",chr(34)*3+codes+chr(34)*3,1))
"""
print(codes.replace("[]",chr(34)*3+codes+chr(34)*3,1))