あどけない話

インターネットに関する技術的な話など

Living in the open world

{-# LANGUAGE TypeSynonymInstances #-}

-- 以下は Alice が定義
type StackA = []

topA :: StackA a -> a
topA = head

popA :: StackA a -> StackA a
popA = tail

pushA :: a -> StackA a -> StackA a
pushA = (:)

-- 以下は Bob が定義

data StackB a = Nil | Cons a (StackB a) deriving Show

topB :: StackB a -> a
topB (Cons x _) = x

popB :: StackB a -> StackB a
popB (Cons x s) = s

pushB :: a -> StackB a -> StackB a
pushB x s = Cons x s

-- 以下は Chris が定義

class Stack s where
    top :: s a -> a
    pop :: s a -> s a
    push :: a -> s a -> s a

instance Stack StackA where
    top = topA
    pop = popA
    push = pushA

instance Stack StackB where
    top = topB
    pop = popB
    push = pushB

move :: (Stack s1, Stack s2) => s1 a -> s2 a -> (s1 a, s2 a)
move s1 s2 = (s1',s2')
  where
    x = top s1
    s1' = pop s1
    s2' = push x s2

動かす。

move [1] Nil
→ ([],Cons 1 Nil)
move (cons 1 Nil) []
→ (Nil,[1])