Created
March 12, 2014 13:46
-
-
Save tenten0213/9507230 to your computer and use it in GitHub Desktop.
Clojure 超入門(via http://qiita.com/ka_/items/a3f79b761e25d485f2a9)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; via http://qiita.com/ka_/items/a3f79b761e25d485f2a9 | |
; Clojure 超入門 | |
(println "Hello World!") | |
; 四則演算 | |
(+ 1 2) | |
(* (+ 1 2) 3) ; (1 + 2) * 3 | |
(* (+ 1 2) (- 3 4)) ; (1 + 2) * (3 - 4) | |
(cons 1 (cons 1 '(2 3))) | |
(first '(1 2 3)) ; 先頭だけ返す | |
(rest '(1 2 3 )) ; 先頭以外返す | |
; 'は遅延評価の為に必要 | |
; 以下は1という関数に2 3 を引数で渡していることになってしまう | |
(1 2 3) ; ClassCastException | |
; ドキュメントや関数の実装は以下で参照 | |
; LightTableだと Ctrl + d でドキュメントが参照できる | |
(doc cons) | |
(source cons) | |
; 関数の作成 | |
(fn [x y] (+ x y)) | |
; このままだと使えない | |
(defn add [x y] (+ x y)) | |
(add 1 2) | |
; 無名関数として使うことも出来る | |
((fn [x y] (+ x y)) 1 2) | |
; 匿名関数 | |
; 無名関数と同様に使えるが、後で呼び出すことは出来ない | |
((fn add-anonymous [x y] (+ x y)) 1 2) | |
(add-anonymous 1 2) ; コンパイルエラー | |
((fn f [x] (if (= x 0) 1 (* x (f (- x 1))))) 10) | |
( | |
(fn f [x] | |
(if (= x 0) | |
1 | |
(* x (f (- x 1))))) | |
10) | |
; ループなぞ要らぬわ | |
; map | |
(map (fn [x] (+ x 1)) '(1 2 3)) | |
; reduce | |
; 1 + 2 + 3 + 4(配列のそれぞれに+という関数を適用) | |
(reduce + '(1 2 3 4)) | |
; filter | |
; 引数の配列から3未満の数値を取り出して配列で返す | |
(filter (fn [x] (< x 3)) '(1 2 3 4)) | |
; nth | |
; 配列の添字2の要素を返す(5) | |
(nth '(1 3 5 7) 2) | |
; take | |
; 配列の先頭から3つ取得 | |
(take 3 '(1 2 3 4 5)) | |
; repeat | |
; そのまま。0を5回リピートしたものから5つ取得(0 0 0 0 0) | |
(take 5 (repeat 0)) | |
; iterate | |
; 0から2づつ足していく。遅延評価?nth実行時に5が渡されて、fnの結果(0 2 4 6 8 10)の添字5の要素が返る | |
(nth (iterate (fn [x] (+ x 2)) 0) 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment