갈루아의 반서재

하스켈 if-else 의 간단한 예를 보자. 

1
2
3
4
5
6
 
*Main> if 1 < 2 then 3 else 4
3
it :: Num a => a
*Main>
 
cs


그럼, 자바에서 어떤가? 자바의 if-else 는 구문이다. 하스켈 if-else 와 유사한 것은 자바의 조건연산자이다. 

아래는 자바 조건(삼항) 연산자의 예로, 값의 도출이 필요할 때 사용할 수 있는 expression 이다.

1
1 < 2 ? 3 : 4 
cs


자바의 if-else 구문은 else-less 형식을 갖지만 하스켈의 ifelse 는 그렇지 않다. 그럼 왜 하스켈은 이것을 허용하지 않는가?

자바의 if-else 와 조건 연산자의 비교는 statement 와 expression 의 차이를 설명하는 훌륭한 예라고 할 수 있다. 


아래 if-else 식의 타입은 무엇일까?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
*Main> if 1 < 2 then 3 else 4
3
it :: Num a => a
*Main>
*Main> :type if 1 <2 then 3 else 4
if 1 <2 then 3 else 4 :: Num a => a
*Main>
*Main> :type if 1 < 2 then 3 else 4.0
if 1 < 2 then 3 else 4.0 :: Fractional a => a
*Main>
*Main> if 1 < 2 then 3 else '4'
 
<interactive>:36:15:
    No instance for (Num Char) arising from the literal ‘3’
    In the expression: 3
    In the expression: if 1 < 2 then 3 else '4'
    In an equation for ‘it’: it = if 1 < 2 then 3 else '4'
*Main>
 
cs


Guards vs. if-else

아래 2가지 버전중 어떤 게 더 나아 보이는가?

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


1
2
3
sign x = if x < 0 then -1
else if x == 0 then 0
else 1
cs

추후에 상기 두 가지 표현법외에 3번째 표현법을 살펴볼 것이다.