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 ??
- Ferenc Nagy
- VIP Member
- Posts: 215
- Joined: 24 Apr 2007 12:26
Use varM or fact variable in place of Money
Nick,foreach Counter = std::downTo(2,0) do
if Money > 100 then
Money = Money - 10
end if
end foreach
In your above trial
Code: Select all
Money = Money - 10
A) Use a fact variable instead of it in lower case.
Code: Select all
facts
money:integer.
...
Code: Select all
money:=IniMoneyValue,
foreach Counter = std::downTo(2,0) do
if money > 100 then
money := money - 10
end if
end foreach
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
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
Frank Nagy
- Thomas Linder Puls
- VIP Member
- Posts: 1410
- Joined: 28 Feb 2000 0:01
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:
Instead of updating variables and looping, we make a recursive invocation of the predicate (corresponding to the next iteration in the loop).
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.
Regards Thomas Linder Puls
PDC
PDC