Discussions related to Visual Prolog
Nick
Posts: 2
Joined: 22 Feb 2014 10:36

Change Variable Value

Unread post by Nick »

Hello guys,

I want to make a foreach loop where every time i will decrease the value of a variable.

For example:

foreach Counter = std::downTo(2,0) do

if Money > 100 then
Money = Money - 10
end if
end foreach


Any proposals please ??
Nick
User avatar
Ferenc Nagy
VIP Member
Posts: 215
Joined: 24 Apr 2007 12:26

Use varM or fact variable in place of Money

Unread post by Ferenc Nagy »

foreach Counter = std::downTo(2,0) do

if Money > 100 then
Money = Money - 10
end if
end foreach
Nick,
In your above trial

Code: Select all

Money = Money - 10
always fails.

A) Use a fact variable instead of it in lower case.

Code: Select all

facts money:integer.
in the clauses

...

Code: Select all

money:=IniMoneyValue, foreach Counter = std::downTo(2,0) do if money > 100 then money := money - 10 end if end foreach
B) Use varM

Money=varM::new("")

Code: Select all

Money::new(IniMoneyValue), foreach Counter = std::downTo(2,0) do if Money:value() > 100 then Money:value := Money:value() - 10 end if end foreach
Take care!
Left := Right is the "set value to the left side" operator,
Left = Right sets the value to the free side of the other is bound. If both sides are bound the '=' operators checks their equality.
TIA, Regards,
Frank Nagy
Nick
Posts: 2
Joined: 22 Feb 2014 10:36

Unread post by Nick »

thanks guys .... i'm kind new user :)
Nick
User avatar
Thomas Linder Puls
VIP Member
Posts: 1399
Joined: 28 Feb 2000 0:01

Unread post by Thomas Linder Puls »

Actually, you should avoid using that kind of imperative programming in Prolog. In Prolog variables are like variables in mathematics: in its scope a variable has one and only one value, the value does not change as result of computation.

As Ferenc Nagy describes, it is possible to apply such methods, but this should not be your standard way of programming. In Prolog you should in general use recursion instead of looping and you should in general use Green immutable variables in favour of black mutable fact variables in your algorithms. The black mutable fact variables should be used to represent the state of your system, not as temporaries in algorithms.

Your code could look like this:

Code: Select all

predicates     strangeCalculation : (positive Counter, integer StartMoney) -> integer Money. clauses     strangeCalculation(Counter, StartMoney) = Money :-         if 0 = Counter then             Money = StartMoney         else             Money = strangeCalculation(Counter-1, StartMoney-10)         end if.
Instead of updating variables and looping, we make a recursive invocation of the predicate (corresponding to the next iteration in the loop).
Regards Thomas Linder Puls
PDC
Post Reply