Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

algorithm - What is the best way to extract a diagonal from a matrix in Haskell?

I was asked to write a function that would extract the diagonal of a matrix stored as a list of lists. The first version was to extract the number by indexing the lists, but I soon concluded it isn't a good algorithm for Haskell and wrote another function:

getDiagonal :: (Num a) => [[a]] -> [a]
getDiagonal [[]]       = []
getDiagonal (xs:[])    = [head xs]
getDiagonal (x:xs)     = head x : getDiagonal (map tail xs)

Since I've only started learning Haskell I'm not sure if it's written in an idiomatic way or if it would perform well.

So my question is is there any better way to extract a diagonal from matrix stored in such a representation or if there isn't is there a better algorithm that could be constructed if the matrix was represented using higher order Haskell concepts, like algebraic types? Also is there any performance difference between deconstructing the list in pattern matching like so ((x:_):xs) or with the head function like shown above?

EDIT: Actually more of curious inquiry than a homework, they don't teach functional programming at technical universities here (which is a pitty I think), but I'll leave the tag.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think using indexing is OK, if you can assume that the argument is a square matrix. Getting diagonal with this representation is O(N2) anyway, since you have to traverse the lists.

diag x = zipWith (!!) x [0..]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...