우리가 만든 함수나 타입들을 다른 곳에서 사용할 수 있게 하려면 module을 만든다. module Shape (...) where -- ...에 외부에서 사용할 수 있게 하려는 함수나 타입을 적어준다. ...body-of-module... 이때 module Shape () where로 하면 아무것도 외부에서 사용할 수 없게 하는 것이고 module Shape where로 하면 모든 함수를 외부에서 사용할 수 있게 하는 것이다. 다른 곳에서 이 module을 사용하려면 import를 한다. import Shape 새로운 data type을 만드려면 data를 사용하고 기존의 type을 이름만 바꾸려면 type을 사용한다. 새로운 data type 만들기. data Shape = Circle Float | Square Float 위 새로운 data type의 의미는 다음과 같다: Shapre에는 두 종류가 있는데 Circle Float의 형태를 가지는 것과 Square Float의 형태를 가지는 것이 있다. 기존의 type 이름만 바꾸어서 사용하기. type Radius = Float 지금까지 공부한 내용으로 Shape의 면적을 계산하는 module을 만들어 보자 -- Shape data type의 경우 아래처럼 외부에서 사용이 필요한 이름만 넣어줄 수 있다. -- Shape의 모든 것을 외부에서 쓸 수 있게 하려면 Shape(...)으로 하면 된다. module Shape (Shape (Rectangle, Ellipse, RtTriangle, Polygon), Radius, Side, Vertex, square, circle, distBetween, area ) where data Shape = Rectangle Side Side | Ellipse Radius Radius | RtTriangle Side Side | Polygon [Vertex] deriving Show -- Show라는 type class를 상속받음을 의미한다. 뒤에서 설명할 것이다. -- Float을 Radius나 Side로 이름은 바꿈으로서 Shape이라는 새 data type에서의 의미를 더 잘 나타낼 수 있다. type Radius = Float type Side = Float type Vertex = (Float, Float) -- Shape의 면적을 계산하는 함수 area :: Shape -> Float area (Rectangle s1 s2) = s1 * s2 area (RtTriangle s1 s2) = s1 * s2 / 2 area (Ellipse r1 r2) = pi * r1 * r2 area (Polygon (v1:vs)) = polyArea vs where polyArea :: [Vertex] -> Float polyArea (v2:v3:vs') = triArea v1 v2 v3 + polyArea (v3:vs') polyArea _ = 0 -- 삼각형의 면적을 계산하는 함수 triArea :: Vertex -> Vertex -> Vertex -> Float triArea v1 v2 v3 = let a = distBetween v1 v2 b = distBetween v2 v3 c = distBetween v3 v1 s = 0.5 * (a+b+c) in sqrt (s*(s-a)*(s-b)*(s-c)) 앞의 세개는 간단하지만 Polygon은 조금 복잡하다. Polygon의 면적 계산 방식은 첫번째 3개의 vertex의 삼각형의 면적을 구하고(v1, v2, v3), 두번째 vertex를 뺀 새 Polygon을 만들고(v1:v3:vs), 다시 첫번째 3개의 vertex의 삼각형의 면적을 구하는 것을 반복하는 것이다. triArea는 삼각형의 면적의 계산인데 Heron's formula이다.
Thursday, August 25, 2011
Chapter 2. A Module of Shapes: Part 1
Subscribe to:
Post Comments (Atom)
Ηеllо frіеnԁs, іts grеat artiсle concerning
ReplyDeletecultureanԁ еntirely defіned, κeeр
іt up all the time.
Also visit my webѕite :: payday loans