2013年2月10日日曜日

開発環境

Real World Haskell』(Bryan O'SullivanJohn GoerzenDon Stewart(著)、山下 伸夫伊東 勝利株式会社タイムインターメディア(翻訳)、オライリー・ジャパン、2009年、ISBN978-4-87311-423-3)の3章(型を定義し、関数を単純化する)の3.13(ガード条件節の評価)の練習問題11.を解いてみる。

11.

コード(BBEdit)

Sample.hs

-- file: Sample.hs
data Cartesian2D = Cartesian2D Double Double
                   deriving (Show)
data Direction = DLeft |
                 DRight |
                 DStraight
                 deriving (Eq, Show)
getDirection :: Cartesian2D -> Cartesian2D -> Cartesian2D -> Direction
getDirections :: [Cartesian2D] -> [Direction]
getDirection (Cartesian2D x1 y1) (Cartesian2D x2 y2) (Cartesian2D x3 y3)
    | crossProduct > 0 = DLeft
    | crossProduct == 0 = DStraight
    | crossProduct < 0 = DRight
        where crossProduct = a * d - b * c
              a = x1 - x2
              b = y1 - y2
              c = x3 - x2
              d = y3 - y2
getDirections [] = []
getDirections (x:xs) | length xs <= 1 = []
                     | otherwise = (getDirection x y z):(getDirections xs)
                         where y = head l
                               z = last l
                               l = take 2 xs
a = Cartesian2D 0 1
b = Cartesian2D 2 4
c = Cartesian2D (-5) 10
d = Cartesian2D 5 (-10)
e = Cartesian2D (-5) (-10)
cartesian2DList = [a, b, c, d, e]

入出力結果(Terminal)

$ ghci
GHCi, version 7.4.2: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> getDirections cartesian2DList
[DRight,DRight,DLeft]
*Main> :quit
Leaving GHCi.
$

0 コメント:

コメントを投稿