Skip to content

Instantly share code, notes, and snippets.

@mizukmb
Created July 15, 2017 09:32
Show Gist options
  • Save mizukmb/dc19cb0a46e200681ff8d1f37675f619 to your computer and use it in GitHub Desktop.
Save mizukmb/dc19cb0a46e200681ff8d1f37675f619 to your computer and use it in GitHub Desktop.
data Vector a = Vector a a a deriving (Show)
vplus :: (Num a) => Vector a -> Vector a -> Vector a
(Vector i j k) `vplus` (Vector l m n) = Vector (i+l) (j+m) (k+n)
dotProd :: (Num a) => Vector a -> Vector a -> a
(Vector i j k) `dotProd` (Vector l m n) = i*l + j*m + k*n
vmult :: (Num a) => Vector a -> a -> Vector a
(Vector i j k) `vmult` m = Vector (i*m) (j*m) (j*m)
@mizukmb
Copy link
Author

mizukmb commented Jul 15, 2017

data Vector a = VVector a a a deriving (Show)

vplus :: (Num a) => Vector a -> Vector a -> Vector a
(VVector i j k) `vplus` (VVector l m n) = VVector (i+l) (j+m) (k+n)

という感じに値コンストラクタを VVector にしてみた。(型コンストラクタと値コンストラクタの違いをわかりやすくするため)

*Main> :l vector.hs 
[1 of 1] Compiling Main             ( vector.hs, interpreted )
Ok, modules loaded: Main.
*Main> Vector 3 5 8 `vplus` Vector 9 2 8

<interactive>:38:1: error:
    • Data constructor not in scope:
        Vector :: Integer -> Integer -> Integer -> Vector a
    • Perhaps you meant ‘VVector’ (line 1)

<interactive>:38:22: error:
    • Data constructor not in scope:
        Vector :: Integer -> Integer -> Integer -> Vector a
    • Perhaps you meant ‘VVector’ (line 1)
*Main> VVector 3 5 8 `vplus` VVector 9 2 8
VVector 12 7 16
*Main> :t Vector

<interactive>:1:1: error:
    • Data constructor not in scope: Vector
    • Perhaps you meant ‘VVector’ (line 1)
*Main> :t VVector
VVector :: a -> a -> a -> Vector a

@mizukmb
Copy link
Author

mizukmb commented Jul 15, 2017

値コンストラクタは引数を渡すと定義された型を返す関数?

関数なので VVector -> Int のように型宣言には使えない( True -> Int とは書けないのと同じ。 True は型じゃない)。

ちなみにデータ型と値コンストラクタの命名は同じにするのが慣例っぽい。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment