Page 1 of 1

Change Variable Value

Posted: 22 Feb 2014 10:43
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 ??

Use varM or fact variable in place of Money

Posted: 22 Feb 2014 12:18
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.

Posted: 22 Feb 2014 13:15
by Nick
thanks guys .... i'm kind new user :)

Posted: 22 Feb 2014 15:17
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).