如何为向量向量创建一个Maybe等价物?

时间:2016-05-15 21:43:53

标签: haskell vector algebraic-data-types

我想让这个工作:

type CharVector = V.Vector Char
type CharMatrix = V.Vector CharVector

data MaybeCharMatrix =
  Nothing
  | CharMatrix

但我无法做到以下事情:

1)模式匹配

test :: MaybeCharMatrix -> Int
test Nothing = -1 -- Doesn't matter, is just to illustrate
test <something> = ? -- Somehow be able to do: cols <something> * rows 

2)导出节目实例:

instance Show MaybeCharMatrix where
  show Nothing = ""
  show <something> = "Cols: " ++ cols <something> ++ ", Rows: " ++ rows <something>

如何实现这一目标?还有其他有效的方法吗?

2 个答案:

答案 0 :(得分:3)

如何使用:

type MaybeCharMatrix = Maybe CharMatrix

test :: MaybeCharMatrix -> Int
test Nothing = -1
test (Just matrix) = ...

这不允许您创建自己的自定义Show实例,因此这是另一个选项:

newtype MaybeCharMatrix = MCM (Maybe CharMatrix)

test :: MaybeCharMatrix -> Int
test (MCM Nothing) = -1
test (MCM (Just matrix)) = ...some function of matrix...

instance Show (MaybeCharMatrix) where
    show (MCM Nothing) = "the nothing string"
    show (MCM (Just matrix)) = ... "Cols: " ++ show (cols matrix) ++ ...

我认为你最好只使用type别名(第一个选项)。然后,您可以使用直接对Maybe值进行操作的所有函数。

show最适用于值的Haskell表示 - 即它应该是有效的Haskell表达式。如果您想要自定义渲染值,只需为渲染函数使用不同的名称 - 例如dumpMatrix

<强>更新

根据您的评论,您需要以下内容:

data MaybeCharMatrix = MyNothing | MyJust CharMatrix

test :: MaybeCharMatrx -> Int
test MyNothing = -1
test (MyJust matrix) = ... can use matrix here ...

instance Show MaybeCharMatrix where
  show MyNothing = "my nothing"
  show (MyJust matrix) = "... Cols: " ++ show (cols matrix) ++ ...

答案 1 :(得分:3)

您的问题在于数据类型声明。通常,类型声明的形式为。

data <type> <args> = <constructor 1> <args>
                   | <constructor 2> <args>
                   | ...
                   | <constructor n> <args>

换句话说,数据声明的每个子句中的第一个表达式被视为数据构造函数。因此,当您使用数据类型时。

data MaybeCharMatrix = Nothing | CharMatrix

Haskell将CharMatrix视为数据构造函数而不是类型。您对Nothing的定义也与标准库定义冲突,因此您应该更改其名称。你真正想要的是这样的。

data MaybeCharMatrix = NothingCM | JustCM CharMatrix

创建一个数据构造函数JustCM,它以CharMatrix为参数。然后,您可以像这样模式匹配。

test :: MaybeCharMatrix -> Int
test NothingCM = -1
test (JustCM mat) = <code>

instance Show MaybeCharMatrix where
    show NothingCM = ""
    show (JustCM mat) = "Cols: " ++ cols mat ++ ", Rows: " ++ rows mat
相关问题