String 从数字到单词的序言

String 从数字到单词的序言,string,recursion,prolog,integer,words,String,Recursion,Prolog,Integer,Words,我正在使用以下谓词将数字转换为单词: word(0):-write('zero')。 单词(1):-写“一”。 单词(2):-写('two')。 单词(3):-写('3')。 单词(4):-写('4')。 单词(5):-写('5')。 单词(6):-写('six')。 单词(7):-写('seven')。 单词(8):-写('8')。 单词(9):-写('9')。 破折号(X):- 写入('-')。%需要在这里添加一些代码,以便在上次挖掘后不打印破折号 num_单词(Nums):- Nums>

我正在使用以下谓词将数字转换为单词:

word(0):-write('zero')。
单词(1):-写“一”。
单词(2):-写('two')。
单词(3):-写('3')。
单词(4):-写('4')。
单词(5):-写('5')。
单词(6):-写('six')。
单词(7):-写('seven')。
单词(8):-写('8')。
单词(9):-写('9')。
破折号(X):-
写入('-')。%需要在这里添加一些代码,以便在上次挖掘后不打印破折号
num_单词(Nums):-
Nums>0,
NMod是Nums mod 10,
NDiv是Nums//10,
单词(NMod),
破折号,

num_words(NDiv)。
解决第一个或最后一个操作必须与其余操作不同的问题的诀窍是将谓词一分为二。在这种情况下,您可以使用调用
单词(数字)
的顶级谓词,然后调用另一个打印数字“尾部”的谓词,始终在数字后添加破折号

此外,您需要重新安排递归,以便稍后计算的数字可以提前打印

num_words(Nums) :-       % This is top-level predicate.
    NDiv is Nums // 10,  % It prints the first digit unconditionally,
    dash_num_words(NDiv),% letting you handle the case when the number is zero.
    NMod is Nums mod 10, 
    word(NMod).

dash_num_words(0).       % When we reach zero, we stop printing.

dash_num_words(Nums) :-  % Otherwise, we follow your algorithm
    Nums > 0,            % with one modification: the dash is printed
    NDiv is Nums // 10,  % unconditionally before printing the digit.
    dash_num_words(NDiv),
    NMod is Nums mod 10,
    word(NMod),
    write('-').

使用本文:只需使用递归谓词即可打印结果列表

word('0') :- write('zero').
word('1') :- write('one').
word('2') :- write('two').
word('3') :- write('three').
word('4') :- write('four').
word('5') :- write('five').
word('6') :- write('six').
word('7') :- write('seven').
word('8') :- write('eight').
word('9') :- write('nine').

num_words(X):- number_chars(X,C), printout(C).

printout([N]):- word(N),!.
printout([N|Tail]):- word(N),write('-'),printout(Tail).
咨询:

?- num_words(1234567890).
 one-two-three-four-five-six-seven-eight-nine-zero
true.
我还更改了用引号括起数字的事实词。如果您不喜欢,我们可以更改它。

有关数字文字的更一般观点,请参阅。来源:

% Grammar for numbers, e.g.
% phrase(number(I),[two,hundred,and,fifty,six]).
% An astonishing characteristic of this code is that it's
% fully bidirectional. The expression
% phrase(number(256),Words)
% will instantiate Words = [two,hundred,and,fifty,six].
% What's more,
% phrase(number(I),Words)
% will eventually instantiate I and Words to all the numbers it knows.
%
% Ken Johnson 17-9-87

好的,这对于解决仪表板问题是有意义的。有没有一种方法可以让我对谓词的调用重新排序,以正确的顺序打印数字,或者我应该改变我的算法?@DomnWerner你说得对,我错过了数字翻转。我重新安排了代码,并添加了一些关于发生了什么的解释。您还可以通过在
printout/1
谓词子句中使用
atom\u number/2
word(N)
之前避免更改OP的事实。