6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Prologで16行でBasicインタプリタを作ってみた。

Posted at

Pythonで書くと数百行かかるというような話をみて、Prologで書いたものあったよな。ないな。書いてみるかと思って書いてみました:

a(V,G,[V|G]).
e(X,I,G,G):-member(X=I,G),!.
e(I,I)-->{integer(I)},!.
e(A+B,I)-->!,e(A,I1),e(B,I2),{I is I1+I2}.
e(X=E,V)-->!,e(E,V),a(X=V),!.
e(E1<E2,I)-->!,e(E1,I1),e(E2,I2),{I1<I2->I=1;I=0},!.
g(I:_,[I:E|Ls],[I:E|Ls]):-!.
g(I:_,[_|Ls],Rs):-!,g(I:_,Ls,Rs).
g(_:_,[],[]).
s(goto(I),_)-->{basic(P),g(I:_,P,Ls)},b(Ls).
s(X=E,Ls)-->!,e(E,V),a(X=V),b(Ls).
s(if(E,E1),Ls)-->!,e(E,V),({V=0} -> b(Ls);s(E1,Ls)).
s(print(E),Ls)-->!,e(E,V),{writeln(V)},b(Ls).
b([])-->!.
b([_:E|Ls])-->s(E,Ls).
run:- basic(P),b(P,[],_).
basic([
10:(a=0),
20:(print(a)),
30:(a=a+1),
40:(if(a<10,goto(20)))
]).
:- run.
:- halt.

SWI-Prologインストール、実行方法と結果

$ apt install swi-prolog
$ swipl a.pl
0
1
2
3
4
5
6
7
8
9

a/1 環境に追加
g/3 gotoの処理
s/4 文の評価
b/3 プログラムの評価
run/0 実行
basic/1 ベーシックのプログラム

最小限の機能しかないですが、これを元に拡張していけば何でも出来るようになると思います。

6
0
0

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
6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?