【发布时间】:2019-10-10 06:59:15
【问题描述】:
我有一个函数,如下所示,Code Review 上的某个人建议我将其重写为完全。他们建议对getRow 和(!) 的调用可以替换为对zip 或fold 的调用。
我已经考虑过这个问题,但我真的不知道如何以这种方式重写它,我也不知道如何自学如何重写它。
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
此代码 sn-p 在我的程序上下文中工作,但如果 n 大于 (ncols mat) - 1 则某些 row ! m 调用将失败。
【问题讨论】:
-
您可以使用
safeGetRow :: Matrix a -> Maybe (Vector a)。如果n“超出范围”,Qustion 是您想要做的。
标签: haskell functional-programming