型の紹介 型クラス Enum、Boundedインスタンス、エラーにならないsucc関数を実装
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT2(型の紹介)、LESSON 13(型クラス)、13.8(練習問題)Q13-3の解答を求めてみる。
コード
lesson/app/Main.hs
module Main where
import Lib (cycleSucc)
main :: IO ()
main = do
print $ cycleSucc (10 :: Int)
print $ cycleSucc (maxBound :: Int)
print $ cycleSucc 'a'
print $ cycleSucc (maxBound :: Char)
lesson/src/Lib.hs
module Lib
( cycleSucc,
)
where
cycleSucc :: (Bounded a, Enum a, Eq a) => a -> a
cycleSucc x =
if x == maxBound
then minBound
else succ x
入出力結果(Terminal, Zsh)
% stack build
lesson-0.1.0.0: unregistering (local file changes: app/Main.hs)
lesson> build (lib + exe)
Preprocessing library for lesson-0.1.0.0..
Building library for lesson-0.1.0.0..
Preprocessing executable 'lesson-exe' for lesson-0.1.0.0..
Building executable 'lesson-exe' for lesson-0.1.0.0..
[2 of 2] Compiling Main
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/lesson-exe/lesson-exe ...
lesson> copy/register
Installing library in /Users/…/lesson/.stack-work/install/x86_64-osx/58a4c4d937f77ed7ad33a3d831dc078cdd38bc2500aef58d99dd5ff42214f933/9.0.2/lib/x86_64-osx-ghc-9.0.2/lesson-0.1.0.0-CIOIkpTgcfQI9akDJnwnSd
Installing executable lesson-exe in /Users/…/lesson/.stack-work/install/x86_64-osx/58a4c4d937f77ed7ad33a3d831dc078cdd38bc2500aef58d99dd5ff42214f933/9.0.2/bin
Registering library for lesson-0.1.0.0..
% stack exec lesson-exe
11
-9223372036854775808
'b'
'\NUL'
%