[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: if
From: |
Fergus Henderson |
Subject: |
Re: if |
Date: |
Tue, 30 Jan 2001 02:56:51 +1100 |
On 29-Jan-2001, Calum Grant <address@hidden> wrote:
> That's not really specific to GNU, but I'll try to answer.
>
> There actually are "if" predicates in Prolog, and alternative branches of
> execution can be taken conditionally. The syntax is just a little different
> and problems tend to be formulated differently. e.g. in an imperative
> language,
>
> printnum(n):
> if(n=1) return "one"
> else if(n=2) return "two"
>
> while in Prolog,
>
> printnum(1, one).
> printnum(2, two).
>
> By default, every "branch" of the printnum predicate is taken, so
> printnum(N, M) would yield two answers: N=1, M=one, N=2, M=two. However if
> you call printnum(2, M), you would just get M=two. The first branch is not
> taken, since the condition N=1 fails.
>
> printnum can also be rewritten as
>
> printnum(N, M) :- N=1, M=one; N=2, M=two.
>
> which makes it even more clear what the conditions are (N=1 or N=2).
That's all true, but it's important to mention Prolog's if-then-else
construct. What you've shown with multiple clauses is more like
Prolog's analog of the `switch' statement in C. But Prolog does
have a very direct analog of if-then-else, in fact it's even called
"if-then-else", although it is spelt `... -> ... ; ...'.
For example,
printnum(n):
if(n=1) return "one"
else return "many"
would be written in Prolog as
printnum(N, M) :-
( N = 1 -> M = "one"
; M = "many"
).
(the parentheses here are optional but highly advisable).
Likewise
printnum(n):
if(n=1) return "one"
if(n=2) return "two"
else return "many"
would be
printnum(N, M) :-
( N = 1 -> M = "one"
; N = 2 -> M = "two"
; M = "many"
).
You can also achieve similar effects using multiple clauses and cut,
but using Prolog's if-then-else is much better style, IMNSHO.
--
Fergus Henderson <address@hidden> | "I have always known that the pursuit
| of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh> | -- the last words of T. S. Garp.
- if, Eduardo Damasio da Costa, 2001/01/29
- RE: if, Calum Grant, 2001/01/29
- Re: if,
Fergus Henderson <=
- Re: if, Ron Stodden, 2001/01/29
- Re: if, Fergus Henderson, 2001/01/29
- Re: if, Ron Stodden, 2001/01/30
- Re: if, Fergus Henderson, 2001/01/30
- Re: if, Ron Stodden, 2001/01/30
- Re: if, Fergus Henderson, 2001/01/30
- RE: if, Calum Grant, 2001/01/31
- Re: if, Ron Stodden, 2001/01/31
- Re: if, Fergus Henderson, 2001/01/31
- RE: if, Calum Grant, 2001/01/30