创建填充为 0 的 Prolog 二维列表
Create Prolog 2d list filled with 0
我想寻求一些帮助来在 Prolog 中创建一个二维列表。
matrix(N, M, MX) :- ... //TODO
?- matrix(2, 3, Mx).
Mx = [[0,0,0],[0,0,0]] ? ;
no
您可以使用 length/2
和 maplist/2
,如下所示:
matrix(Nrows, Ncols, Matrix) :-
length(Matrix, Nrows),
length(Row, Ncols),
maplist(=(0), Row),
maplist(=(Row), Matrix).
使用 length/2
您可以创建 n 个变量的列表:
?- length(Row, 3).
Row = [_28380, _28386, _28392].
使用maplist/2
,您可以将变量列表的每个元素实例化为所需的值:
?- length(Row, 3), maplist(=(0), Row).
Row = [0, 0, 0].
创建行后,您可以创建矩阵:
?- length(Row, 3), maplist(=(0), Row), length(Matrix, 2), maplist(=(Row), Matrix).
Row = [0, 0, 0],
Matrix = [[0, 0, 0], [0, 0, 0]].
示例:
?- matrix(2, 3, M).
M = [[0, 0, 0], [0, 0, 0]].
我想寻求一些帮助来在 Prolog 中创建一个二维列表。
matrix(N, M, MX) :- ... //TODO
?- matrix(2, 3, Mx).
Mx = [[0,0,0],[0,0,0]] ? ;
no
您可以使用 length/2
和 maplist/2
,如下所示:
matrix(Nrows, Ncols, Matrix) :-
length(Matrix, Nrows),
length(Row, Ncols),
maplist(=(0), Row),
maplist(=(Row), Matrix).
使用 length/2
您可以创建 n 个变量的列表:
?- length(Row, 3).
Row = [_28380, _28386, _28392].
使用maplist/2
,您可以将变量列表的每个元素实例化为所需的值:
?- length(Row, 3), maplist(=(0), Row).
Row = [0, 0, 0].
创建行后,您可以创建矩阵:
?- length(Row, 3), maplist(=(0), Row), length(Matrix, 2), maplist(=(Row), Matrix).
Row = [0, 0, 0],
Matrix = [[0, 0, 0], [0, 0, 0]].
示例:
?- matrix(2, 3, M).
M = [[0, 0, 0], [0, 0, 0]].