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

问题描述

如何将类似[[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.

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

09-11 16:23