2014年1月22日水曜日

開発環境

Real World Haskell―実戦で学ぶ関数型言語プログラミング(Bryan O'Sullivan (著)、 John Goerzen (著)、 Don Stewart (著)、山下 伸夫 (翻訳)、伊東 勝利 (翻訳)、株式会社タイムインターメディア (翻訳)、オライリージャパン)の3章(型を定義し、関数を単純化する)、3.13(ガードの条件節の評価)、練習問題 11.を解いてみる。

その他参考書籍

練習問題 11.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}
module Main where

getDirections :: [Point] -> [Direction]
getDirections (a:b:c:xs) = getDirection a b c:getDirections (b:c:xs)
getDirections _ = []

type Point = (Double, Double)
data Direction = Clockwise | Collinear | Counterclockwise
                deriving (Show)

getDirection :: Point -> Point -> Point -> Direction
getDirection a b c
    | cow a b c < 0 = Clockwise
    | cow a b c > 0 = Counterclockwise
    | otherwise = Collinear

cow :: Point -> Point -> Point -> Double
cow (x1, y1) (x2, y2) (x3, y3) = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)

入出力結果(Terminal, インタプリタghci)

$ ghci
GHCi, version 7.6.3: 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> let a = (0.0,0.0)
*Main> let b = (1.0,0.0)
*Main> let c = (1.0,1.0)
*Main> let d = (2.0,1.0)
*Main> let e = (2.0,0.0)
*Main> getDirections [a, b, c, d, e]
[Counterclockwise,Clockwise,Clockwise]
*Main> getDirections [a, b, c, d, (3.0,1.0)]
[Counterclockwise,Clockwise,Collinear]
*Main> getDirections [a, b]
[]
*Main> :quit
Leaving GHCi.
$

0 コメント:

コメントを投稿