【问题标题】:Haskell create list from newtype dataHaskell 从新类型数据创建列表
【发布时间】:2015-10-09 07:45:59
【问题描述】:

这是一项家庭作业。我们得到了一个新类型的矩阵,它是教授对抽象矩阵的实现。我的主要问题是如何创建 Matrix 类型的列表。我需要实现的第一个函数 fillWith 采用一个元组,它是要创建的矩阵的(行数、列数)以及要放置在每个索引处的数据。

module Matrix (Matrix, fillWith, fromRule, numRows, numColumns, 
           at, mtranspose, mmap, add, mult) 
where

-- newtype is like "data", but has some efficiency advantages
newtype Matrix a = Mat ((Int,Int),(Int,Int) -> a)

--fillWith   :: (Int,Int) -> a -> (Matrix a)
--fillWith ix val = Mat ((, 


--trying to create a row of type Matrix
row_matrix :: [a] -> Matrix a
row_matrix ls = Mat ((1, length ls), (\x y -> if x > 1 then undefined else ls !! (y-1)))

【问题讨论】:

  • Matrix 的这个定义很糟糕。你可以告诉你的教授我是这么说的。 Unidiomatic,与只是有点奇怪的data Matrix a = Mat { width, height :: Int, members :: (Int, Int) -> a }相比,我对效率获胜的说法提出异议。
  • 您可能想问一个关于新类型与数据声明的问题 with the specific definition .

标签: haskell matrix newtype


【解决方案1】:

您只是缺少一些括号和逗号:

row_matrix ls = Mat ((1, length ls), (\(x,y) -> if x > 1 then undefined else ls !! (y-1)))
                                       ^-^-^--- add these

Mat 是一个元组,其中:

  • 第一个元素本身就是一个元组,并且
  • 第二个元素是一个将元组转换为a类型值的函数

您可以始终使用wherelet 子句来简化值的构造,例如:

row_matrix as = Mat (bounds, accessor)
  where bounds = (1, length as)
        accessor (i,j) = if i > 1 then undefined else as !! (j-1)

使用where 子句使代码更具可读性。

要实现fillWith,我会遵循相同的方法:

fillWith bounds val = Mat (bounds, accessor)
  where accessor (i,j) = ???

我认为现在很明显 ???应该是。

【讨论】:

  • 基本上,但是用编译器检查你的答案;有很多写法,例如accessor (i,j) = valaccessor = \(i,j) -> valaccessor = const val
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
  • 2012-04-06
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
相关资源
最近更新 更多