此转置功能如何工作? [英] How does this transpose function work?
问题描述
我的教授提供了该功能,我不知道实际发生了什么.
I have this function given by my professor and I have no idea what is actually happening.
这里是计算m×n矩阵的转置的函数:
Here is the function that computes the transpose of an m-by-n matrix:
let rec transpose = function
| [] -> failwith "cannot transpose a 0-by-n matrix"
| []::xs -> []
| xs -> List.map List.head xs :: transpose (List.map List.tail xs)
测试功能:
> transpose [[1;2;3];[4;5;6]];;
val it : int list list = [[1; 4]; [2; 5]; [3; 6]]
我了解List.map,递归和所有其他内容.我只是不明白为什么/如何使用此功能.任何澄清将不胜感激!谢谢!
I understand List.map, recursion and all that stuff. I just do not understand why/how this function works. Any clarifications will be much appreciated! Thanks!
推荐答案
假设我们有一个3x3矩阵A
.
Say we have a 3x3 matrix A
.
let A =
[ [1;2;3]
[4;5;6]
[7;8;9] ]
= [ R1
R2
R3 ]
现在,让我们分析一下转置函数.
Now, let's analyse the transpose function.
let rec transpose = function
| [] -> failwith "cannot transpose a 0-by-n matrix"
| []::xs -> []
| xs -> List.map List.head xs :: transpose (List.map List.tail xs)
前2个案例捕获了以下事件:
The first 2 cases catch the events where:
- 该列表为空列表
- 该列表包含一个空列表,表示所有内部列表均已处理
代码[1]
List.map List.head xs
将内部列表映射到其各自的head元素
maps the inner lists to their respective head elements
R1.Head ; R2.Head ; R3.Head
= 1 ; 4 ; 7
= C1
代码[2]
transpose (List.map List.tail xs)
(递归)转置斩首列表的尾部.
因此,在每次递归中,一列都会转置为一行.
然后,使用::
关键字将这些行用于构造结果列表.
(recursivly) transposes the tails of the beheaded lists.
So on each recursion a column gets transposed into a row.
Using the ::
keyword these rows are then used to construct the resulting list.
transpose A
= C1 :: C2 :: C3 :: []
= [ C1
C2
C3 ]
= [ [1;4;7]
[2;5;8]
[3;6;9] ]
这篇关于此转置功能如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!