LoginSignup
79
62

More than 5 years have passed since last update.

REPLを実装する

Last updated at Posted at 2015-11-09

プログラミング言語に触れてたらREPLを実装したくなるじゃないですか。

Read-eval-print loopの略
字のごとく読んで評価して表示して繰り返す。対話型評価環境を指す。

REPLとは - はてなキーワード

なるほどね。

(loop (print (eval (read))))

右から順に読んで“Read-Eval-Print Loop”でたしかにREPLだ。

この記事の内容を実行して途中で停止したいときはCtrl+DとかCtrl+C

Rubyでやってみよう。

% ruby -e'loop{p eval gets}'
1 + 2 * 3
7
"Pixiv".downcase
"pixiv"

うん、ばっちりだね。“Gets-Eval-P Loop”でGEPLだ。

PHPだとちょっと長くなる。

% php -r'while(1){ $code = sprintf("\$result = %s;", fgets(STDIN)); eval($code); var_dump($result); }'
1 + 2 * 3
int(7)
strtolower("Pixiv")
string(5) "pixiv"

“Vardump-Eval-Fgets While”でVEFWだ。なにがなんだか。

Python(2.7)ではどうか。ワンライナーで書くのがたいへんつらい。

% python -c "while True:
    print(input())
"
1 + 2 * 3
7
"Pixiv".lower()
pixiv

なんでかわかんないけど、Python 2系のinput()eval(raw_input(prompt))と同じです。誰が得するんだろう… とみんな思ったのか、Python 3000のinput()は2系のraw_input()と同じです。

“Input-Print While”でIPWだ。もしくは“Rawinput-Eval-Print-While”でREPWか!

最後に

適当にLispでは〜 みたいなことを書いたけど、実はCommon Lispをまともに書いたことがないのでやってみた。

% sbcl
This is SBCL 1.2.16, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.

SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses.  See the CREDITS and COPYING files in the
distribution for more information.
* (loop (print (eval (read))))
(+ 1 (* 2 3))

7
debugger invoked on a END-OF-FILE in thread
#<THREAD "main thread" RUNNING {1002C74753}>:
  end of file on #<SB-SYS:FD-STREAM for "standard input" {100632C013}>

Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

restarts (invokable by number or by possibly-abbreviated name):
  0: [ABORT] Exit debugger, returning to top level.

(SB-IMPL::INPUT-CHAR/UTF-8 #<SB-SYS:FD-STREAM for "standard input" {100632C013}> T 0)
0] (string-downcase "Pixiv")

"pixiv"
0] ^D
*

よくわかんないけど、デフォルトのプロンプト*が出てないので動いてる気がした。(もしかしたら動いてないのかも)

あとPerlを勉強してみようかと思ったけどデータ型がよくわかなかったので諦めた。

79
62
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
79
62