序言:DCGS - 将数字转换为英文

问题描述:

我正在练习在Prolog中使用DCG。我取一个123这样的整数,将它'爆炸'到一个列表中,即[1,2,3],然后我想使用DCG规则来获得输出一二三。到目前为止,我可以转换一个整数列表,例如[1]合并成一个,但我不知道在列表中做什么。我想尽可能多地使用DCG,因为这正是我正在练习的。这里是我当前的代码:序言: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]. 

一个可能的解决方案,而采用DCG中就是我以前写的,但我不知道如何使用DCG中写。

% 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

问题是什么? – 2011-01-09 07:52:12

+1

你好,抱歉,基本上我想把一个整数转换成一个英文单词列表,所以123变成[一,二,三]。我希望能够使用DCG语法规则来做到这一点。我已经给出了一个非DCG的例子,所以你可以看到我想要的。我认为这可以使用DCG规则解决?那足够的信息了吗?谢谢。 – ale 2011-01-09 10:30:35

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

例子:

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