長方形を表現
SICPの問題2.3。長方形を表し、周囲の長さと面積を計算する手続きを作る。
今回は、問題2.2とほぼ同じなので、以下にソースと実行結果を示します。
$cat rectangle.hs data Point = Point Integer Integer instance Show Point where show (Point x y ) = "( "++show(x)++" , " ++ show(y)++" )" data Rectangle = Rectangle Point Point instance Show Rectangle where show (Rectangle (Point x y) (Point x' y')) = show (Point x y) ++ " - " ++ show (Point x' y) ++ "\n" ++ show (Point x y') ++ " - " ++ show (Point x' y') makeRectangle:: Integer->Integer->Integer->Integer->Rectangle makeRectangle x y x' y' = Rectangle (Point x y) (Point x' y') getCircuit::Rectangle->Integer getCircuit (Rectangle (Point x y) (Point x' y')) = double $( getLength x x') + (getLength y y') where double = (*) 2 getDimension (Rectangle (Point x y) (Point x' y')) = (*) (getLength x x') (getLength y y') getLength::Integer->Integer->Integer getLength x x' = abs ( x' -x )
$ghci rectangle.hs Loading package base-1.0 ... linking ... done. Compiling Main ( rectangle.hs, interpreted ) Ok, modules loaded: Main. *Main> makeRectangle 3 5 6 1 ( 3 , 5 ) - ( 6 , 5 ) ( 3 , 1 ) - ( 6 , 1 ) *Main> let rect = makeRectangle 3 5 6 1 *Main> getCircuit rect 14 *Main> getDimension rect 12