그 밖의 유용한 함수와 매크로

그 밖의 유용한 함수와 매크로 (Other Useful Functions and Macros)

Clojure 코어에서 자주 쓰이는 함수·매크로들을 주제별로 모아 둔 페이지예요. 함수 만들기, 출력, 정규식 지원과 함께 관련 기능들을 정리해 봤어요.

출처: Clojure 공식 문서 - Other Useful Functions and Macros

본문

불리언 및 비교 함수: = == identical? not= not true? false? nil?

기타: identity dotimes time assert with-open

함수 만들기 (Creating functions)

함수 예시 표현식 반환 값
fn (map (fn [x] (+ 2 x)) [1 2 3]) (3 4 5)
리더 매크로 #() (map #(+ 2 %) [1 2 3]) (3 4 5)
partial (map (partial + 2) [1 2 3]) (3 4 5)
comp (map (comp - *) [2 4 6] [1 2 3]) (-2 -8 -18)
complement (map (complement zero?) [3 2 1 0]) (true true true false)
constantly (map (constantly 9) [1 2 3]) (9 9 9)

출력 (Printing)

객체를 pass:[*out*]의 현재 값인 출력 스트림에 출력하는 여러 함수가 제공돼요. -str 변형들은 pass:[*out*]를 StringWriter에 바인딩하고 거기에 출력한 다음 결과 문자열을 반환해요. pr은 객체를 출력하는데, 둘 이상이면 공백으로 구분해요. prn은 같은 작업을 하고 뒤에 newline을 붙여요. printprintln은 각각 prprn을 호출하되 pass:[*print-readably*](기본값 true)를 nil로 바인딩해요. 이렇게 하면 문자열이 주변 따옴표나 이스케이프 문자 인코딩 없이 출력되고, 문자는 선행 \나 이스케이프 문자 인코딩 없이 출력돼요. 기본적으로 prprn은 리더가 객체를 읽을 수 있는 방식으로 출력하며, printprintln은 사람이 읽기 위한 출력을 만들어요. pass:[*print-readably*]가 non-nil일 때 메타데이터의 출력은 pass:[*print-meta*](기본값 nil)에 의해 토글돼요.

관련 함수

pass:[*out*]로 출력: pr prn print println newline

문자열로 출력: pr-str prn-str print-str println-str with-out-str

정규식 지원 (Regex Support)

정규식 패턴은 #"pattern" 리더 매크로로 읽기 시점에, 또는 re-pattern으로 런타임에 컴파일될 수 있어요. 두 형태 모두 java.util.regex.Pattern 객체를 생성해요.

user=> (re-seq #"[0-9]+" "abs123def345ghi567")
("123" "345" "567")
user=> (re-find #"([-+]?[0-9]+)/([0-9]+)" "22/7")
["22/7" "22" "7"]
user=> (let [[a b c] (re-matches #"([-+]?[0-9]+)/([0-9]+)" "22/7")]
         [a b c])
["22/7" "22" "7"]
user=> (re-seq #"(?i)[fq].." "foo bar BAZ QUX quux")
("foo" "QUX" "quu")

관련 함수

re-matcher re-find re-matches re-groups re-seq

더 알아보기