Show instance for matrix in Haskell

前端 未结 1 1788
忘了有多久
忘了有多久 2021-01-28 03:48

I\'ve been trying to create a show instance in order to visualize a given matrix and also, to create an outline with columns around and in between the matrix. What I managed to

相关标签:
1条回答
  • 2021-01-28 03:55

    If you make the assumptions that all rows of a matrix have the same number of columns (or at least that the first row of any matrix has at least as many columns as any other), and that three dashes suffice as the border for any cell, you can calculate the number of dashes to use between rows by taking the length of the leading row.

    If these assumptions do not hold, you need to make one pass over the array to calculate the maximum width of any row, then a second pass to draw the matrix. If matrices can contain numbers outside the range [0..9], you would also need to calculate the width of each column.

    The algorithm might be:

    1. Map each number in the matrix to a String, generating a [[String]].
    2. Generate a list of column widths, whose elements are the maximum width of any row’s element in that column.
    3. Left-pad every string in the [[String]] with spaces to its column width.
    4. Concatenate the columns of each row, adding the appropriate separator between elements and the appropriate left and right borders. The result is a [String] whose elements are the graphical representation of each row.
    5. If you wish to add horizontal rules above, below, or between the rows, take the length of any element of the [String] (As all columns are now padded to their maximum width, all rows should now have the same length.) and generate that number of box-drawing characters, such as ASCII "---" or Unicode "┌─┬─┐".
    6. Concatenate the rows and the separator lines into a String separated by newlines.

    As Rein Henrichs mentioned in a comment, you might consider naming this function something other than show.

    0 讨论(0)
提交回复
热议问题