【问题标题】:Calling a newtype constructor调用新类型构造函数
【发布时间】:2015-10-19 18:45:23
【问题描述】:

我并没有真正了解如何在 Haskell 中使用模块,我对这门语言真的很陌生,到目前为止我只知道最基本的东西,比如创建一个函数之类的东西。现在我收到一个错误,上面写着

Not in scope: data constructor 'Mat'

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

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) =&gt; Show (Matrix a) 的意思是,他们只是给了我们这段代码,然后告诉我们在没有解释任何这些事情发生的情况下弄清楚它。

如果有人可以帮助我,我将不胜感激。我猜想在 Haskell 中打印矩阵的内容是非常基本的,我确信我让它变得比它应该的更困难,但作为这种语言的新手,我不太确定我是什么有时在做。

【问题讨论】:

    标签: haskell matrix


    【解决方案1】:

    导出构造函数:

    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)) = ...
    

    【讨论】:

    • 我改变了它,但它仍然告诉我“不在范围内:数据构造函数'Mat”'
    • @Argus 检查您是否在更改后重新编译了模块。 GHCi 也应该在不显式重新编译的情况下接受更改。
    猜你喜欢
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2018-07-21
    相关资源
    最近更新 更多