型と型クラス

9.3 型の別名と付け替え

newtype宣言について


昨日時間切れで作りきれなかったnewtype宣言のサンプル。
まぁ、悩んだ分理解が深まりました。

  • example5.hs
newtype MyListNT a = MkMyListNT [a]

myList :: MyListNT Int
myList = MkMyListNT [1, 2, 3, 4]

top :: (MyListNT a) -> a
top (MkMyListNT []) = undefined
top (MkMyListNT (x:_)) = x

pop :: (MyListNT a) -> (MyListNT a)
pop (MkMyListNT []) = MkMyListNT []
pop (MkMyListNT (_:xs)) = MkMyListNT xs

main = do print $ top myList
          print $ top $ pop myList
          print $ top $ pop $ pop myList
          print $ top $ pop $ pop $ pop myList


関数の型宣言とパターンマッチの部分で悩みました。

top :: MyListNT a -> a
top MkMyListNT [] = undefined
top MkMyListNT (x:_) = x


と書いていて

% ghc -W -o example5 example5.hs

example5.hs:7:4:
    Constructor `MkMyListNT' should have 1 argument, but has been given 0
    In the pattern: MkMyListNT
    In the definition of `top': top MkMyListNT [] = undefined


と怒られ続けていました。カッコがいるんですね。
めでたし、めでたし。