Home > Archive > Prolog > May 2006 > how to make a list of N 1s
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
how to make a list of N 1s
|
|
|
| Hi,
how can I construct a list L of all 1s with a length N.
I mean,
when I call makelist(3, L), I want it to produce L=[1,1,1].
thanks in advance...
| |
|
| makeN1(N, L) :-
N == 0, !,
L = []
;
N1 is N - 1,
L = [1 | Tail],
makeN1(N1, Tail).
| |
| Markus Triska 2006-04-26, 7:03 pm |
| erhan wrote:
> makeN1(N, L) :-
n_ones(N, Os) :-
length(Os, N),
maplist(=(1), Os).
| |
| michael.goodrich@gmail.com 2006-04-26, 7:03 pm |
|
erhan wrote:
> Hi,
>
> how can I construct a list L of all 1s with a length N.
>
> I mean,
> when I call makelist(3, L), I want it to produce L=[1,1,1].
>
> thanks in advance...
makeOnes(0,[]).
makeOnes(N,[1|T]) :- N1 is N-1, makeOnes(N1,T).
| |
|
| makeOnes(0,[]).
makeOnes(N,[1|T]) :- N1 is N-1, makeOnes(N1,T).
this does not work, when I say makeones(3,L), it finds L=[1,1,1], but
if I say find another solution by typing ";" it enters into a infinite
loop...
but a slight modification make it work. here it is:
makeOnes(0,[]) :- !.
makeOnes(N,[1|T]) :- N1 is N-1, makeOnes(N1,T).
anyway, thank you very much...
| |
| michael.goodrich@gmail.com 2006-04-27, 7:03 pm |
| Good catch.
| |
| ralphbecket@gmail.com 2006-04-27, 7:03 pm |
| erhan wrote:
> Hi,
>
> how can I construct a list L of all 1s with a length N.
makelist(N, Xs) :-
Ones = [1 | Ones],
length(Xs, N),
append(Xs, _, Ones).
How it works is left as an exercise for the student.
-- Ralph
| |
| Nick Wedd 2006-05-02, 8:02 am |
| In message <1146183614.239084.289820@e56g2000cwe.googlegroups.com>,
ralphbecket@gmail.com writes
>erhan wrote:
>
>makelist(N, Xs) :-
> Ones = [1 | Ones],
> length(Xs, N),
> append(Xs, _, Ones).
>
>How it works is left as an exercise for the student.
When I read this last night, it struck me as clever, hard to understand,
and dirty. Now that I have understood it and slept on it, it strikes me
as the clean, sensible, and natural way to generate this list. Why have
I never been taught this technique before?
Nick
--
Nick Wedd nick@maproom.co.uk
|
|
|
|
|