3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Haskellで空間を実装してみた

Last updated at Posted at 2014-11-08

Haskellの実験メモです。

空間について勉強したらHaskellで実装してみたくなりました。

※ 遊びなので厳密さは考慮していません。Vectorとか名前が微妙ですが、割り切っています。

  • 型クラスのインスタンスに型シノニムを使えるようにするためFlexibleInstances拡張を使用しています。
  • 空間の拡張を型クラスの継承で表現しています。
{-# LANGUAGE FlexibleInstances #-}

class VectorSpace a where
    (@+) :: a -> a -> a
    (@*) :: Double -> a -> a

class VectorSpace a => NormedSpace a where
    norm :: a -> Double

class NormedSpace a => UnitarySpace a where
    innerProduct :: a -> a -> Double

type Vector = (Double, Double)

instance VectorSpace Vector where
    (x1, y1) @+ (x2, y2) = (x1 + x2, y1 + y2)
    a @* (x, y) = (a * x, a * y)

instance NormedSpace Vector where
    norm (x, y) = sqrt (x ^ 2 + y ^ 2)

instance UnitarySpace Vector where
    innerProduct (x1, y1) (x2, y2) = x1 * x2 + y1 * y2

print2 a b = do
    putStr a
    print b

main = do
    let a = (1.0, 2.0) :: Vector
        b = (3.0, 4.0) :: Vector
    print2 "a = " a
    print2 "b = " b
    print2 "a @+ b = " $ a @+ b
    print2 "3 @* a = " $ 3 @* a
    print2 "3 @* b = " $ 3 @* b
    print2 "norm a = " $ norm a
    print2 "norm b = " $ norm b
    print2 "innerProduct a b = " $ innerProduct a b
実行結果
a = (1.0,2.0)
b = (3.0,4.0)
a @+ b = (4.0,6.0)
3 @* a = (3.0,6.0)
3 @* b = (9.0,12.0)
norm a = 2.23606797749979
norm b = 5.0
innerProduct a b = 11.0

参考

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?