调用newtype构造函数

时间:2015-10-19 18:45:24

标签: haskell matrix

我真的不知道如何使用Haskell中的模块,我对这种语言很陌生,到目前为止我只知道最基本的东西,比如创建一个函数和那种东西。现在我收到的错误是

Not in scope: data constructor 'Mat'

这应该是矩阵的newtype定义的构造函数。这是模块:

module Matrix (Matrix, fillWith, fromRule, numRows, numColumns, at, mtranspose, mmap) where
newtype Matrix a = Mat ((Int,Int), (Int,Int) -> a)

fillWith :: (Int,Int) -> a -> (Matrix a)
fillWith (n,m) k = Mat ((n,m), (\(_,_) -> k))

fromRule :: (Int,Int) -> ((Int,Int) -> a) -> (Matrix a)
fromRule (n,m) f = Mat ((n,m), f)

numRows :: (Matrix a) -> Int
numRows (Mat ((n,_),_)) = n

numColumns :: (Matrix a) -> Int
numColumns (Mat ((_,m),_)) = m

at :: (Matrix a) -> (Int, Int) -> a
at (Mat ((n,m), f)) (i,j)| (i > 0) && (j > 0) || (i <= n) && (j <= m) = f (i,j)

mtranspose :: (Matrix a) -> (Matrix a)
mtranspose (Mat ((n,m),f)) = (Mat ((m,n),\(j,i) -> f (i,j)))

mmap :: (a -> b) -> (Matrix a) -> (Matrix b)
mmap h (Mat ((n,m),f)) = (Mat ((n,m), h.f))

我用这种方式在我自己的模块上调用它:

module MatrixShow where
    import Matrix


    instance Matrix (Show a) => Show (Matrix a) where 
        show Mat ((x,y),(a,b)) = show 1

节目1只是一个测试。我甚至不确定那是什么

instance Matrix (Show a) => Show (Matrix a)意味着,他们只是给了我们这个代码,然后告诉我们要解决它而不解释任何这些事情发生了什么。

如果有人能帮助我,我会很感激。我猜测打印矩阵的内容在Haskell中是非常基本的,而且我确信我会让它变得比它应该更难,但是作为这种语言的新手我还不确定我是什么有时做。

1 个答案:

答案 0 :(得分:5)

导出构造函数:

module Matrix (Matrix(..), fillWith, fromRule, -- etc.
                --   ^^^^

默认情况下,仅导出类型,阻止其他模块访问构造函数。

该行

instance Matrix (Show a) => Show (Matrix a) where

对我来说不对。周围有一些Matrix班吗?更有可能的是,它应该阅读

instance (Show a) => Show (Matrix a) where

此外,该行

show Mat ((x,y),(a,b)) = show 1

错了。它的左侧应该看起来像

show (Mat ((x,y), f)) = ...
相关问题