Pls look at the following segment
Author Message
Pls look at the following segment

Quote:

> generate_code(Pegs, Code) :-
>    random(1,6,N),
>    colours(N,Y),
>    append(Code, Y, C),
>    P is Pegs - 1,
>    P > 0, % if P > 0
>    generate_code(P, C).

> I write the above code for generating a list of code of
> length Pegs, however, it fail.

generate_code(P,_)

is true if
P>0
and
generate_code(NP,_) where NP is P-1 is true.

How could that possibly be true?

Use two instances of generate_code instead.

Quote:
> PLs mail to me.

You did not supply a legal mail address.

--
Jon                                       http://www.*-*-*.com/ ~bratseth/

Thu, 22 Jul 1999 03:00:00 GMT
Pls look at the following segment

Quote:

>?- use_module(library(random)).
>?- use_module(library(lists)).

>colours(1,r).
>colours(2,g).
>colours(3,y).
>colours(4,b).
>colours(5,p).

Fine so far...

Quote:
>generate_code(Pegs, Code) :-
>   random(1,6,N),
>   colours(N,Y),
>   append(Code, Y, C),
>   P is Pegs - 1,
>   P > 0, % if P > 0
>   generate_code(P, C).

One problem is that you have a type error: you call

colours(_, Y)

and

append(_, Y, _)

but the second argument of colours/2 is always a colour (one of {r,g,y,p,b})
whereas the second argument of append/3 is always a list.

Another problem is that if generate_code is supposed to be called with
the second argument free, there is no producer for the second argument
(i.e. you have a mode error); and on the other hand, if the second
argument is supposed to be bound, the code is still wrong, because you
never use the value of the second argument.

Another problem is that you have written an recursive predicate with
no base case, so it is bound to either fail or loop forever.

Quote:
>I write the above code for generating a list of code of
> length Pegs, however, it fail.
>Could anyone tell me why ?

It could fail if random(1, 6, N) returns a number that is not in the
range 1 to 5.  It will also fail if P =< 0 --- and since you're
decrementing P each recursive call, this will happen eventually.

--

WWW: <http://www.cs.mu.oz.au/~fjh>   |  of excellence is a lethal habit"

Thu, 22 Jul 1999 03:00:00 GMT
Pls look at the following segment

Quote:

> generate_code(Pegs, Code) :-
>    random(1,6,N),
>    colours(N,Y),
>    append(Code, Y, C),
>    P is Pegs - 1,
>    P > 0, % if P > 0
>    generate_code(P, C).

> I write the above code for generating a list of code of
>  length Pegs, however, it fail.

There is no clause that succeeds when Pegs =< 1 .
--
Manuel Carro

||         Manuel Carro -- CLIP Group         ||

||    http://www.clip.dia.fi.upm.es/~boris    ||
|| Phone: +34 1 336-7448  FAX: +34 1 352-4819 ||

Mon, 26 Jul 1999 03:00:00 GMT

 Page 1 of 1 [ 3 post ]

Relevant Pages