了解在Haskell这个矩阵转置功能矩阵、功能、Haskell

2023-09-11 05:35:16 作者:悲哀的现实

这矩阵转置函数的工作原理,但我试图理解它一步一步execurtion,我不明白这一点。

This matrix transposition function works, but I'm trying to understand its step by step execurtion and I don't get it.

    transpose:: [[a]]->[[a]]
    transpose ([]:_) = []
    transpose x = (map head x) : transpose (map tail x)

transpose [[1,2,3],[4,5,6],[7,8,9]]

返回:

 [[1,4,7],[2,5,8],[3,6,9]]

我不明白怎么连接运算符正与地图。它是串联x的每个磁头在相同的函数调用?怎么样?

I don't get how the concatenation operator is working with map. It is concatenating each head of x in the same function call? How?

这是

(map head x)

创建每个列表的头元素的列表?

creating a list of the head elements of each list?

推荐答案

让我们来看看功能是否为你的榜样输入的内容:

Let's look at what the function does for your example input:

transpose [[1,2,3],[4,5,6],[7,8,9]]
<=>
(map head [[1,2,3],[4,5,6],[7,8,9]]) : (transpose (map tail [[1,2,3],[4,5,6],[7,8,9]]))
<=>
[1,4,7] : (transpose [[2,3],[5,6],[8,9]])
<=>
[1,4,7] : (map head [[2,3],[5,6],[8,9]]) : (transpose (map tail [[2,3],[5,6],[8,9]]))
<=>
[1,4,7] : [2,5,8] : (transpose [[3],[6],[9]])
<=>
[1,4,7] : [2,5,8] : (map head [[3],[6],[9]]) : (transpose (map tail [[3],[6],[9]]))
<=>
[1,4,7] : [2,5,8] : [3, 6, 9] : (transpose [[], [], []])
<=>
[1,4,7] : [2,5,8] : [3, 6, 9] : [] -- because transpose ([]:_) = []
<=>
[[1,4,7],[2,5,8],[3,6,9]]

请注意,在其中我选择减少的条件的顺序,是不一样的评价顺序的haskell将使用,但是这并没有改变的结果。

Note that the order in which I chose to reduce the terms, is not the same as the evaluation order haskell will use, but that does not change the result.

编辑:在回答你的编辑问题:

In response to your edited question:

这是

(map head x)

     

创建每个列表的头元素的列表?

creating a list of the head elements of each list?

是的,它是。

 
精彩推荐
图片推荐