計算機科学のブログ

型の紹介 型クラス Int型、Enum型クラス、succ関数、Bounded型クラス、minBoundとmaxBound

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT2(型の紹介)、LESSON13(型クラス)、13.8(練習問題)Q13-2の解答を求めてみる。

コード

inc :: Int -> Int
inc = (+) 1

maxInt :: Int
maxInt = maxBound :: Int

minInt :: Int
minInt = minBound :: Int

main = do
  print $ inc maxInt
  print minInt
  -- 以下はエラー
  print $ succ maxInt

入出力結果(Terminal, Zsh)

% ghci
GHCi, version 8.10.7: https://www.haskell.org/ghc/  :? for help
Loaded package environment from /Users/…/.ghc/x86_64-darwin-8.10.7/environments/default
:macro 'doc' overwrites builtin command.  Use ':def!' to overwrite.
(0.00 secs, 0 bytes)
(0.00 secs, 0 bytes)
Loaded GHCi configuration from /Users/…/.ghc/ghci.conf
Prelude
λ> :info Enum
type Enum :: * -> Constraint
class Enum a where
  succ :: a -> a
  pred :: a -> a
  toEnum :: Int -> a
  fromEnum :: a -> Int
  enumFrom :: a -> [a]
  enumFromThen :: a -> a -> [a]
  enumFromTo :: a -> a -> [a]
  enumFromThenTo :: a -> a -> a -> [a]
  {-# MINIMAL toEnum, fromEnum #-}
  	-- Defined in ‘GHC.Enum’
instance Enum Word -- Defined in ‘GHC.Enum’
instance Enum Ordering -- Defined in ‘GHC.Enum’
instance Enum Integer -- Defined in ‘GHC.Enum’
instance Enum Int -- Defined in ‘GHC.Enum’
instance Enum Char -- Defined in ‘GHC.Enum’
instance Enum Bool -- Defined in ‘GHC.Enum’
instance Enum () -- Defined in ‘GHC.Enum’
instance Enum Float -- Defined in ‘GHC.Float’
instance Enum Double -- Defined in ‘GHC.Float’
Prelude
λ> :quit
Leaving GHCi.
% runghc sample2.hs 
-9223372036854775808
-9223372036854775808
sample2.hs: Prelude.Enum.succ{Int}: tried to take `succ' of maxBound
%