如何在prolog中转置矩阵 [英] How to transpose a matrix in prolog

查看:23
本文介绍了如何在prolog中转置矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 [[1,2,3][4,5,6][6,7,8]] 之类的列表转置为 [[1,4,6],[2,7,8],[3,6,9]]?

How can I transpose a list like [[1,2,3][4,5,6][6,7,8]] to [[1,4,6],[2,7,8],[3,6,9]]?

描绘它:我想将矩阵向左翻转 90 度.我该怎么做?

To depict it: I'd like to flip the matrix 90 degree to the left. How can I do that?

推荐答案

不确定你的例子是否正确,但我明白了.

Not sure your example is correct, but I get the idea.

如果使用 SWI-PROLOG,您可以使用 CLPFD 模块,例如所以:

If using SWI-PROLOG, you can use the CLPFD module, like so:

:- use_module(library(clpfd)).

允许你使用 transpose/2 谓词,像这样:

Allowing you to use the transpose/2 predicate, like this:

1 ?- transpose([[1,2,3],[4,5,6],[6,7,8]], X).
X = [[1, 4, 6], [2, 5, 7], [3, 6, 8]].

否则(如果没有 SWI-PROLOG),您可以简单地使用这个实现(恰好是 SWI 的 clpfd 中的旧实现):

Otherwise (if no SWI-PROLOG), you could simply use this implementation (which happened to be an old one in SWI's clpfd):

transpose([], []).
transpose([F|Fs], Ts) :-
    transpose(F, [F|Fs], Ts).

transpose([], _, []).
transpose([_|Rs], Ms, [Ts|Tss]) :-
        lists_firsts_rests(Ms, Ts, Ms1),
        transpose(Rs, Ms1, Tss).

lists_firsts_rests([], [], []).
lists_firsts_rests([[F|Os]|Rest], [F|Fs], [Os|Oss]) :-
        lists_firsts_rests(Rest, Fs, Oss).

有关使用 foldl 和 maplist 内置插件的更新版本,请参阅 clpfd.pl.

For an updated version which uses foldl and maplist built-ins, see clpfd.pl.

这篇关于如何在prolog中转置矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆