갈루아의 반서재

하스켈 연산자는 중위폼이 적용된 함수라고 볼 수 있다. 연산자에 대해서 더 알고 싶으면 아래와 같이 :info 를 사용한다.

1
2
3
4
5
6
 
Prelude> :info (^)
(^) :: (Num a, Integral b) => a -> b -> a       -- Defined in ‘GHC.Real’
infixr 8 ^
Prelude>
 
cs

여기서 (Num a, Integral b) => a -> b -> a 가 의미하는 것은 첫 번째 피연산자는 number 이고 두 번째는 integer 여야 한다는 것이다. infixr 8 의 의미는 right-associative 이고, 8의 우선순위를 갖는다는 의미이다. 


하스켈 연산자의 우선순위에 대해서는 아래를 참조한다.

PrecedenceOperatorDescriptionAssociativity
9

highest

.Function compositionRight
8^,^^,**PowerRight
7*,/,`quot`,`rem`,`div`,`mod`Left
6+,-Left
5:Append to listRight
4==,/=,<,<=,>=,>Compare-operators
3&&Logical ANDRight
2||Logical ORRight
1>>,>>=Left
1=<<Right
0$,$!,`seq`Right

https://rosettacode.org/wiki/Operator_precedence#Haskell


다른 연산자에 대해서도  :info 를 이용해 살펴보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Prelude> :info (==)
class Eq a where
  (==) :: a -> a -> Bool
  ...
        -- Defined in ‘GHC.Classes’
infix 4 ==
 
 
Prelude> :info (>)
class Eq a => Ord a where
  ...
  (>) :: a -> a -> Bool
  ...
        -- Defined in ‘GHC.Classes’
infix 4 >
 
 
Prelude> :info (+)
class Num a where
  (+) :: a -> a -> a
  ...
        -- Defined in ‘GHC.Num’
infixl 6 +
 
 
Prelude> :info (*)
class Num a where
  ...
  (*) :: a -> a -> a
  ...
        -- Defined in ‘GHC.Num’
infixl 7 *
 
 
Prelude> :info (||)
(||) :: Bool -> Bool -> Bool    -- Defined in ‘GHC.Classes’
infixr 2 ||
Prelude> :info (^^)
(^^) :: (Fractional a, Integral b) => a -> b -> a
        -- Defined in ‘GHC.Real’
infixr 8 ^^
 
 
Prelude> :info (**)
class Fractional a => Floating a where
  ...
  (**) :: a -> a -> a
  ...
        -- Defined in ‘GHC.Float’
infixr 8 **
Prelude>
 
cs


연산자를 함수처럼 사용하기 위해서는 괄호로 닫아야 한다. 

1
2
3
4
 
Prelude> (+) 3 4
7
Prelude>
cs


이와는 반대로 역따옴표로 함수를 감싸서 연산자처럼 사용할 수도 있다.

1
2
3
4
Prelude> 3 `add` 4
7
Prelude> 11 `rem` 3
2
cs


하스켈에서는 사용자 정의 연산자도 만들 수 있다. ! # $ % & * + . / < = > ? @ \ ^ | - ~ : 와 non-ASCII 유니코드 심볼은 커스톰 연산자에 사용할 수 있다.