2017年2月11日土曜日

開発環境

関数プログラミング入門(Richard Bird (著)、山下伸夫 (翻訳)、オーム社)の第2章(単純なデータ型)、2.3(列挙)、練習問題2.3.1、2.3.2、2.3.3を取り組んでみる。

練習問題2.3.1、2.3.2、2.3.3

コード(Emacs)

data Day = Sun | Mon | Tue | Wed | Thu | Fri | Sat
  deriving (Eq, Ord, Enum, Show)

-- 2.3.1
dayBefore :: Day -> Day
dayBefore d = if n == 0
              then Sat
              else toEnum (n - 1)
  where n = fromEnum d

-- 2.3.2
data Direction = North | South | East | West
               deriving (Eq, Ord, Enum, Show)

reverse :: Direction -> Direction
reverse d
  | d == North = South
  | d == South = North
  | d == East = West
  | d == West = East

-- 2.3.3
data Bool = True | False deriving (Eq, Enum, Show)

入出力結果(Terminal, ghci)

$ ghci sample3.hs
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main             ( sample3.hs, interpreted )
Ok, modules loaded: Main.
*Main> dayBefore Sun
Sat
*Main> dayBefore Mon
Sun
*Main> dayBefore Sat
Fri
*Main> reverse North

<interactive>:4:1: error:
    Ambiguous occurrence ‘reverse’
    It could refer to either ‘Prelude.reverse’,
                             imported from ‘Prelude’ at sample3.hs:1:1
                             (and originally defined in ‘GHC.List’)
                          or ‘Main.reverse’, defined at sample3.hs:16:1
*Main> Main.reverse North
South
*Main> Main.True
True
*Main> Main.True == Main.False
False
*Main> Main.True == Main.True
True
*Main> Main.False == Main.True
False
*Main> Main.False == Main.False
True
*Main> :q
Leaving GHCi.
$

0 コメント:

コメントを投稿