2016-05-15 4 views
1

私はこの作業を取得しようとしています:aベクトルを作成するには?

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

'data MaybeCharMatrix = Nothing | CharMatrix' - ここでCharMatrixはAFAIKというコンストラクタです。** CharMatrixとも呼ばれるタイプではありません。 – immibis

答えて

3

は、使用についての方法:ちょうど使用して、私はあなたがオフに優れていると思う

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 MaybeCharMatrix = Maybe CharMatrix 

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

ので、ここで別のオプションですtypeエイリアス(最初のオプション)。次に、Maybeの値を直接操作するすべての関数を直接使用することができます。

showは、値のハスケル表現に最もよく使用されます。つまり、有効なハスケル表現でなければなりません。値のカスタムレンダリングが必要な場合は、レンダリング関数に別の名前を使用してください。 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) ++ ... 
+0

それは私のせいです。質問は私が欲しいものの単純化されたケースです。それは概念の単なる例でした。私は問題の背後に概念を実装することができるようにしたいと考えています(学習目的のため)。申し訳ありませんが十分に明確でない場合。 – OneEyeQuestion

+0

回答が更新されました。 – ErikR

3

を。一般に、型宣言は形式のものです。

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

他の言い方をすれば、データ宣言の各節の最初の式は、データコンストラクタとみなされます。したがって、データ型を使用したとき。

data MaybeCharMatrix = Nothing | CharMatrix 

Haskellは、データコンストラクタないタイプとしてCharMatrixを扱います。 Nothingの定義も標準ライブラリ定義と矛盾するので、その名前を変更する必要があります。あなたが本当に欲しいのは、このようなものです。引数としてCharMatrixを取るデータコンストラクタJustCMを作成

data MaybeCharMatrix = NothingCM | 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 
+0

あなたの答えは受け入れますが、他の人は最初に答えました。ごめんなさい。 – OneEyeQuestion

関連する問題