LoginSignup
0
0

More than 3 years have passed since last update.

HaskellでMonadを使って簡単な複素数の計算プログラム

Last updated at Posted at 2020-07-17

HaskellでFunctorを使って簡単な複素数の足し算プログラム
HaskellでFunctorを使って簡単な複素数の足し算プログラムーその2

以前Functorで簡単な計算をするプログラムを作り、今回はMonadで試してみました。

HaskellでMonadを使って簡単な複素数の計算プログラム

Complex.hs
data ComplexNumber n = Z n n

class ComplexFunctor t where
    cfmap :: (a -> b) -> (a -> b) -> t a -> t b

class (ComplexFunctor c) => ComplexApplicative c where
    cpure :: a -> a -> c a
    (<**>) :: c(a -> b) -> c a -> c b

class ComplexMonad c where
    creturn :: a -> a -> c a
    (>>==) :: c a -> (a -> a -> c b) -> c b

instance ComplexFunctor ComplexNumber where
    cfmap func1 func2 (Z a b) = Z (func1 a) (func2 b)

instance ComplexApplicative ComplexNumber where
    cpure a b = Z a b

    (Z func1 func2) <**> c = cfmap func1 func2 c

instance ComplexMonad ComplexNumber where
    creturn a b = Z a b
    Z a b >>== f = f a b

main::IO()
main = do
    let a ans = (\(Z a b) -> (a,b) ) ans

    let ans = cpure (+) (+) <**> Z 1 2 <**> Z 3 4

    print (a ans)

    let add a1 b1 a2 b2 = creturn (a1 + a2) (b1 + b2)
    let sub a1 b1 a2 b2 = creturn (a2 - a1) (b2 - b1)

    let ans2 = creturn 3 4 >>== add 4 5 >>== add 10 20 >>== add 20 30 >>== sub 7 9

    print (a ans2)

FunctorとApplicativeの部分は前回と同じです。
add関数とsub関数は、それぞれ加算、減算する関数で、4引数取ります。
>>==関数のところで最初の2引数を部分適用して、実部と虚部を加減算します。

実行結果
(4,6)
(30,50)
0
0
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
0
0