I've written this function to give the neighbours of a vertex in a graph:

import Data.Matrix (Matrix, getRow, ncols)
import Data.Vector ((!))

type AdjacencyMatrix = Matrix Bool

-- Input: the graph's adjacency matrix and a vertex. 
-- Output: the list of neighbours of that vertex.
neighbours :: AdjacencyMatrix -> Int -> [Int]
neighbours mat n = filter (\m -> row ! m) [0..(ncols mat)-1]
        where row = getRow n mat

Someone suggested here to replace my partial calls to getRow and (!) with calls to zip and/or fold. I can't really see how this would be done. Does anyone have suggestions of how to improve this?

  • 2
    \$\begingroup\$ Are you looking for a review or a rewrite? Keep in mind this is Code Review and please take a look at our help center. \$\endgroup\$ – Mast May 23 '19 at 7:09
  • \$\begingroup\$ I think I was initially looking for a rewrite, though I would be glad to receive anyone's review. \$\endgroup\$ – Curran McConnell May 23 '19 at 14:02
  • 1
    \$\begingroup\$ neighbours n = findIndices id . getRow n \$\endgroup\$ – Gurkenglas May 24 '19 at 12:09
  • \$\begingroup\$ Thanks, @Gurkenglas. I think I need to familiarize myself a bit better with some of the utility functions in these libraries. \$\endgroup\$ – Curran McConnell May 24 '19 at 19:54
  • 1
    \$\begingroup\$ I made that suggestion under the assumption that the matrix package would offer a function like rows :: Matrix a -> [[a]] or Matrix a -> Vector (Vector a). The output of such a function could be easily consumed with list transforms to produce the graph. Sadly matrix doesn't offer any functions like these. \$\endgroup\$ – sjakobi May 27 '19 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.