2011-09-19 60 views
2

我有一个关于如何衡量一个词的问题。 单词中的每一个字母都具有特定的权重,我需要计算该单词的总权重。 例如:Sicstus Prolog - 一个词的重量

A-E = 1, F-O = 2, P-Z = 3. 

如果字是 “PEN”,答案是 “我的体重= 6”,

cuz P = 3, E = 1 and N = 2. 

我已经试过:

word_weight([X], W):- 
    X = 65 -> W = 1; 
    X = 66 -> W = 3. 
word_weight([X,Y],W):- 
    X = 65 -> W1 = 1; 
    X = 66 -> W1 = 3, 
    Y = 65 -> W2 = 1; 
    Y = 66 -> W2 = 3, 
    W is W1 + W2. 
word_weight([X|Y], W):- 
    X = 65 -> W = 1; 
    X = 66 -> W = 3, 
    word_weight(Y, W). 

水库运行: | ? - word_weight(“B”,W)。
W = 3? 是

它只能用一个字母。如何使它与许多字母一起使用?答案将是重量的总值。

回答

2

以下程序适用于SWI-Prolog。它肯定很容易适应Sicstus Prolog。

char_weight(C, 1) :- C >= 65, C =< 69. 
char_weight(C, 2) :- C >= 70, C =< 79. 
char_weight(C, 3) :- C >= 80, C =< 90. 

word_weight([], 0). 
word_weight([Char| Chars], Weight) :- 
    char_weight(Char, W), 
    word_weight(Chars, Ws), 
    Weight is W + Ws. 
+0

非常感谢! – Ferry

2

如何

weight(C, 1) :- char_code('A') =< C, C =< char_code('E'). 
weight(C, 2) :- char_code('F') =< C, C =< char_code('O'). 
weight(C, 3) :- char_code('P') =< C, C =< char_code('Z'). 

word_weight(S, W) :- string(S), !, string_list(S, L), word_weight(L, W). 
word_weight([], 0). 
word_weight([H|T], W) :- W is weight(H) + word_weight(T). 

在eclipse-CLP,string_list/2一个字符串转换成数字小字符代码列表,char_code/2得到一个字符的数字代码。

编辑: 哎呀,我应该已经完整阅读你的问题:

  • 文使用->/2,你应该使用括号,不要犹豫使用缩进: (Condition -> IfBranch ; ElseBranch ), RestProg. 你的第二个子句是有点不可读。但对于这个练习,根本不需要->/2
  • 您的第三条款仅适用于单字母字符串,因为它首先将W与X的值合并,然后希望将W与X的权重统一。只有当Y和X具有相同的权重时,这才起作用。
+1

F-O,但是你的规则读取A-O,类似于P-Z。 –

+0

对,谢谢,改变了, – chs

+0

Thx 4帮助! – Ferry