갈루아의 반서재

현재까지 살펴본 함수를 정의하는 일반적인 형식은 다음과 같다. 

let name param1 param2 ... paramN = expression


주어진 3개의 값의 최소값을 계산하는 min3 라는 함수를 정의해보자. Prelude는 min 이라는 함수를 가지고 있다. 이를 이용해서 작성해보자.

1
2
3
4
5
6
7
 
Prelude> let min3 a b c = min a (min b c)
min3 :: Ord a => a -> a -> a -> a
 
Prelude> min3 5 2 10
2
it :: (Num a, Ord a) => a
cs


Guards

아래 함수는 3가지 경우를 대비하여 가드를 사용한 예이다. 

1
2
3
sign x | x < 0 = -1
       | x == 0 = 0
       | otherwise = 1
cs


Notes:

• l:load 를 통해 파일로 부터 함수 정의를 호출할 수 있다.

• 기호 x 는 한 번 등장한다.  가드는 다음줄에 와도 된다.

• 가드는 | 과 = 사이에 있고, Bool 을 반환한다.


가드를 사용해서 min 함수같은 작은 숫자를 출력하는 함수를 정의해보자. 

guard1.hs

1
2
3
smaller x y
    | x <= y = x
    | otherwise = y
cs


1
2
3
4
5
6
7
8
9
10
11
12
Prelude> :load guard1
[1 of 1] Compiling Main             ( guard1.hs, interpreted )
 
guard1.hs:3:1: Warning: Tab character
Ok, modules loaded: Main.
 
*Main> smaller 7 10
7
it :: (Num a, Ord a) => a
*Main> smaller 'z' 'a'
'a'
it :: Char
cs


화씨 80 이상이면 hot, 70 이상이면 nice, 그리고 나머지는 cold 로 기온을 기준으로 날씨를 분류하는 함수를 만들어보자. 

1
2
3
weather temp | temp >= 80 = "Hot!"
             | temp >= 70 = "Nice!"
             | otherwise = "Cold!"
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
*Main> :load guard2
[1 of 1] Compiling Main             ( guard2.hs, interpreted )
 
guard2.hs:3:1: Warning: Tab character
Ok, modules loaded: Main.
*Main> weather 95
"Hot!"
it :: [Char]
*Main>
*Main> weather 32
"Cold!"
it :: [Char]
*Main>
*Main> weather 75
"Nice!"
it :: [Char]
cs