Вопрос

I have some atoms that stand for the numbers 1 to 4 for example.

Like

number(one).
number(two).
number(three).
number(four).

Now I have to write a predicate that checks if the first number is bigger then the second one.

istBiggerThen(X,Y) :-
    (  X < Y
       -> true
       ;  false
    ).

But now I can only ask sth like

isBiggerThan(3,4).

But I want to

isBiggerThan(three,four).

How can I do that? Please help me :) Thanks in advance.

Это было полезно?

Решение

One way is to add facts that "map" English atoms to numeric values, and then use these facts to do comparisons, additions, and so on:

numericValue(one, 1).
numericValue(two, 2).
numericValue(three, 3).
numericValue(four, 4).

Now you can do this:

istBiggerThen(XinEng,YinEng) :-
    numericValue(XinEng, X),
    numericValue(YinEng, Y),
    /* The rest of your code goes here */
    (  X < Y -> true ;  false).

Note that numericValue/2 can be used both ways - to convert names to numbers, and to convert numbers to names. For example, you can write a predicate that computes / checks the sum of two atoms spelled out using English names of the corresponding numbers.

Другие советы

It can be done without mapping atoms to numeric values:

num(one).
num(two).
num(three).
num(four).

isBiggerThan(X, Y) :-
    findall(Value, num(Value), Numbers),
    nth1(IndexX, Numbers, X),
    nth1(IndexY, Numbers, Y),
    IndexX > IndexY.

Sample input and output:

?- isBiggerThan(three,two).
true .

?- isBiggerThan(one,four).
false.
greater(X,Y,Greater):-
        X > Y, Greater is X.
    
greater(X,Y,Greater):-
        X =< Y, Greater is Y.

I've stumbled on this question almost eight years later but I think it's interesting. I saw a pattern for this while learning OCaml.

To define numbers atomically, each number is defined by being greater than the previous number. All numbers greater than the next number are also greater than the current number.

greater(one,zero).
greater(two,one).
greater(three,two).
greater(four,three).

greater(X, zero):- greater(X, one).
greater(X, one):- greater(X, two).
greater(X, two):- greater(X, three).
greater(X, three):- greater(X, four).
?- greater(four,one).
true.

?- greater(two,four).
false.

?- greater(zero,two).
false.

?- greater(three,zero).
true.

In english:

one is greater than zero
two is greater than one
three is greater than two
four is greater than three

greater than one means greater than zero
greater than two means greater than one
greater than three means greater than two
greater than four means greater than three
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top