갈루아의 반서재

require 를 사용해서 자신의 이름공간에서 라이브러리를 사용할 수 있는 3가지 방법


1) 이름공간을 인수로 받아 require 를 사용하는 것

clojure.set 이름공간이 REPL이 시작될 때 로딩된다. 그렇지 않은 경우 require 를 사용해서 작업을 직접할 수 있다.

1
2
3
4
5
6
7
8
9
 
user=> (clojure.set/union #{:r :b :w} #{:w :p :y})
#{:y :r :w :b :p}
user=>
 
user=> (require 'clojure.set)
nil
user=>
 
cs

2) :as 를 사용해서 require 의 별칭 기능을 이용하는 것

심볼 이름 앞에 원래의 이름공간 대신 별칭을 붙여서 심볼에 접근할 수 있다.

1
2
3
4
5
6
7
8
9
10
 
user=> (ns wonderland)
nil
wonderland=> (require '[alice.favfoods :as afl])
nil
 
wonderland=> afl/fav-food
"strawberry jam"
wonderland=>
 
cs

require 를 직접 사용할 수 있지만, 보통 ns 안에서 키워드와 벡터의 형태로 사용한다.

1
2
3
4
5
6
7
8
 
user=> (ns wonderland
  #_=>  (:require [alice.favfoods :as af]))
nil
wonderland=> af/fav-food
"strawberry jam"
wonderland=>
 
cs

3) require 를 이름공간, :refer, :all 옵션과 함께 사용하는 방법

이름공간의 모든 심볼이 로딩되고 현재의 이름공간에서 심볼 이름만으로 직접 접근할 수 있다. 

이 방법은 이름 충돌이 발생할 수 있어 위험하다. 

1
2
3
4
5
6
 
wonderland=> (ns wonderland
        #_=>  (:require [alice.favfoods :refer :all]
        #_=>            [rabbit.favfoods :refer :all]))
nil
 
cs


토끼가 좋아하는 음식과 앨리스가 좋아하는 음식을 입력받아, 둘이 모두 좋아하는 음식을 반환하는 함수를 만들어보자. 

 1) clojure.set 이름공간을 불러들이고 s 라는 별칭을 만들어 사용한다. 

1
2
3
4
uer=> (ns wonderland
 #_=>     (:require [clojure.set :as s]))
nil
 
cs

2) food1 의 집합은 food-set1 심볼에 바인딩된다. 이와 마찬가지로 food2 의 집합은 food-set2 심볼에 바인딩된다. 

3) clojure.set 이름공간의 intersection 함수와 심볼 food-set1, food-set2 를 사용한다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
wonderland=> (defn common-fav-foods [foods1 foods2]
        #_=>     (let [food-set1 (set foods1) ;
        #_=>           food-set2 (set foods2) ;
        #_=>           common-foods (s/intersection food-set1 food-set2)] ;
        #_=>         (str "Common Foods: " common-foods)))
#'wonderland/common-fav-foods
wonderland=>
 
wonderland=> (common-fav-foods [:jam :brownies :toast]
        #_=>                   [:lettuce :carrot :jam])
"Common Foods: #{:jam}"
wonderland=>
 
cs