2011-01-08 8 views
1

私はPrologでDCGを使って練習しています。私は123のような整数をとり、それをリスト[すなわち1,2,3]に「分解」してから、DCGルールを使用して出力を1,2,3にしたいと考えています。今のところ私は1つの整数のリストを変換することができます。 [1]を1つにするが、リストになるときに何をすべきかわからない。これは私が練習しているものなので、できるだけ多くのDCGを使用したいと思っています。ここに私の現在のコードがあります:Prolog:DCGS - 数字を英語に変換する

tests(1, [1]). 
tests(2, [67]). 
tests(3, [183]). 
tests(4, [999]). 

numToEng(N, Res) :- 
    tests(N, W), 
    print('test: '),print(W),nl, 
    explode(W, Exploded), 
    print('exploded: '),print(Exploded),nl, 
    phrase(num(Res), Exploded). 

explode(N, Explosion) :- 
    explode(N, [], Explosion). 
explode(0, Explosion, Explosion) :- !.  
explode(N, Inter, Explosion) :- 
    Test is N mod 10, 
    NewN0 is N - Test, 
    NewN1 is NewN0//10, 
    explode(NewN1, [Test|Inter], Explosion). 

num(X) --> digit(X).  

digit(zero) --> [0]. 
digit(one) --> [1]. 
digit(two) --> [2]. 
digit(three) --> [3]. 
digit(four) --> [4]. 
digit(five) --> [5]. 
digit(six) --> [6]. 
digit(seven) --> [7]. 
digit(eight) --> [8]. 
digit(nine) --> [9]. 

DCGsを使用せずに、可能な解決策は、私が以前に書いたものですが、私はDCGsを使用して作成する方法を思ったんだけど。

% test cases, called by numToEng/2 
tests(1, [1]). 
tests(2, [67]). 
tests(3, [183]). 
tests(4, [999]). 

% dictionary 
digit(0,zero). 
digit(1,one). 
digit(2,two). 
digit(3,three). 
digit(4,four). 
digit(5,five). 
digit(6,six). 
digit(7,seven). 
digit(8,eight). 
digit(9,nine). 

% take an integer e.g. 123 and explode it 
% into a list i.e. [1,2,3] 
explode(N, Explosion) :- 
    explode(N, [], Explosion). 
explode(0, Explosion, Explosion) :- !.  
explode(N, Inter, Explosion) :- 
    Test is N mod 10, 
    NewN0 is N - Test, 
    NewN1 is NewN0//10, 
    explode(NewN1, [Test|Inter], Explosion). 

% take a number in digits and convert it 
% into english e.g. [1,2,3] would be 
% [one,two,three] 
numToEng(N, Res) :- 
    tests(N, Test), 
    explode(Test, Exploded), 
    numToEng(N, Exploded, [], Res). 
numToEng(_, [], Rev, Res) :- 
    reverse(Rev, Res). 
numToEng(N, [H|T], Inter, Res) :- 
    digit(H, Word), 
    numToEng(N, T, [Word|Inter], Res). 
+0

質問は何ですか? –

+1

こんにちは、申し訳ありませんが、基本的に整数を英単語のリストに変換したいので、123は[1、2、3]になります。私はDCGの文法規則を使ってこれを行うことができるようにしたい。 DCG以外の例を与えて、私が望むものを見ることができます。私はこれがDCGルールを使って解決できると思いますか?十分な情報ですか?ありがとう。 – ale

答えて

3
digits([]) --> []. 
digits([D|Ds]) --> digit(D), digits(Ds). 

例:

?- explode(123,X), digits(Digits,X,[]). 
X = [1, 2, 3], 
Digits = [one, two, three] 
+0

、それは恥ずかしいほど明らかです:p。 – ale

関連する問題