建立一个n长度相同值的列表Prolog

时间:2013-05-07 20:05:09

标签: list prolog

我希望在build/3元素的Prolog中N列表,每个元素应为X

?- build(30,3,L).  
L = [30,30,30].  

花了好几个小时,继续无限循环或变量没有正确实例化。

build(_,0,[]).  
build(X,N1,[X]):- N1>0, N1 is N - 1, build(X,N,[]).  
build(X,N1,[X|L]) :- N1 > 0, N1 is N - 1, build(X,N,L).  

2 个答案:

答案 0 :(得分:6)

使用元谓词使其非常简短:

(1)with DateTime:创建一个长度为N的列表,然后将其所有元素与X匹配。

using(var con = new SqlConnection(conString))
using(var cmd = con.CreateCommand())
{
    cmd.CommandText = @"insert into tblnewaccount
                        values (@id, @date)";
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = dateTimePicker1.Value;
    con.Open();
    cmd.ExecuteNonQuery();
}

(2)with maplist/2:循环N次并用X次完成List

build(X, N, List)  :- 
    length(List, N), 
    maplist(=(X), List).

答案 1 :(得分:5)

build(_,0,[]).         % any value, repeated 0 times, makes for an empty list

好。

build(X,N1,[X|L]) :-   % a value X, repeated N1 times, makes for [X|L] list, _if_ ...
  N1 > 0, N1 is N - 1,    %  N1 is positive, and L is
  build(X,N,L).           %  one element shorter... right?

非常好。嗯?你的意思是N is N1 - 1

build(X,N1,[X]):- N1>0, N1 is N - 1, build(X,N,[]).  

为什么? [X]已与之前的规则[X] = [X | [] ] = [X | L]匹配,空列表L = []将与第一条规则匹配。

您根本不需要此规则