갈루아의 반서재

대부분의 functional languages 와 마찬가지로, 하스켈의 리스트는 "cons" 리스트이다. 

"cons" 리스트는 2개의 부분으로 구성된다. 

  • head: a value
  • tail: a list of values (빈 리스트도 가능)

: ("cons") 연산은 값과 동일한 타입의 값으로 구성된 리스트(혹은 빈 리스트)로부터 새로운 리스트를 생성한다.

1
2
3
4
5
6
7
8
 
Prelude> 5 : [10,20,30]
[5,10,20,30]
it :: Num a => [a]
 
Prelude> :type (:)
(:) :: a -> [a] -> [a]
 
cs


cons (:) 연산은 값과 리스트로부터 새로운 리스트를 만든다.

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
 
Prelude> let a = 5
a :: Num a => a
 
Prelude> let b = [10,20,30]
b :: Num t => [t]
 
Prelude> let c = a:b
c :: Num a => [a]
 
Prelude> c
[5,10,20,30]
it :: Num a => [a]
 
Prelude> head c
5
it :: Num a => a
 
Prelude> tail c
[10,20,30]
it :: Num a => [a]
 
Prelude> let d = tail (tail c)
d :: Num a => [a]
 
Prelude> d
[20,30]
it :: Num a => [a]
 
cs


cons 노드는 다수의 cons 노드에 의해 참조되어질 수 있다.

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
 
Prelude> let a = 5
a :: Num a => a
 
Prelude> let b = [10,20,30]
b :: Num t => [t]
 
Prelude> let c = a:b
c :: Num a => [a]
 
Prelude> let d = tail (tail c)
d :: Num a => [a]
 
Prelude> let e = 2:d
e :: Num a => [a]
 
Prelude> let f = 1:c
f :: Num a => [a]
 
Prelude> c
[5,10,20,30]
it :: Num a => [a]
 
Prelude> d
[20,30]
it :: Num a => [a]
 
Prelude> e
[2,20,30]
it :: Num a => [a]
 
Prelude> f
[1,5,10,20,30]
it :: Num a => [a]
 
cs


다음 표현식의 값은 무엇인가?

1
2
3
4
5
6
7
8
9
10
11
12
 
Prelude> 1:[2,3]
[1,2,3]
it :: Num a => [a]
 
Prelude> 1:2
 
<interactive>:112:1:
    Non type-variable argument in the constraint: Num [a]
    (Use FlexibleContexts to permit this)
    When checking that ‘it’ has the inferred type
      it :: forall a. (Num a, Num [a]) => [a]
cs


1
2
3
4
5
6
7
8
Prelude> chr 97:chr 98:chr 99:[]
 
<interactive>:114:1: Not in scope: ‘chr’
 
<interactive>:114:8: Not in scope: ‘chr’
 
<interactive>:114:15: Not in scope: ‘chr’
 
cs


1
2
3
4
5
Prelude> import Data.Char
Prelude Data.Char> chr 97:chr 98:chr 99:[]
"abc"
it :: [Char]
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
Prelude Data.Char> []:[]
[[]]
it :: [[t]]
Prelude Data.Char> [1,2]:[]
[[1,2]]
it :: Num t => [[t]]
Prelude Data.Char> []:[1]
 
<interactive>:127:1:
    Non type-variable argument in the constraint: Num [t]
    (Use FlexibleContexts to permit this)
    When checking that ‘it’ has the inferred type
      it :: forall t. Num [t] => [[t]]
cs

cons 는 우측결합이다.

chr 97:(chr 98:(chr 99:[]))