views:

65

answers:

2

Is there anything in Prolog that works like a for loop and if then condition?

+1  A: 

If you are looking for such kinds of statements then you are not thinking in Prolog :)

Just kidding, by the way there aren't plain translation or for and if/else, but you can think about how they should be in prolog:

  • an if/else statement can be obtained by just having two rules that match over different conditions
  • a for loop can be done with two recursive rules, one is the base case and it doesn't depends upon itself to keepon while the other does what you intend to do inside the loop and follows itself..
Jack
-1: there is an if-then-else construct in Prolog, and it's quite useful in complicated rules.
larsmans
yes there is, but you should avoid using it, and we're not talking about complicated rules. If you teach someone a bad habit before a good one you'll never recover :)
Jack
IMHO, it should not be avoided, it should be taught. If we don't teach it, people will start writing programs with red cuts in them.
larsmans
+2  A: 

if/then/else can be obtained with (->)/2 and (;)/2:

(    If ->
     Then
;    Else
)

Sometimes this is useful. In general though (when the condition contains variables), it will make your programs unsound and incomplete. Whenever it is possible to describe the conditions with pattern matching, you should use pattern matching instead. You can then not only check but also generate solutions.

mat