add Clojure and its dialects to /samples

This commit is contained in:
Hoàng Minh Thắng
2013-04-15 13:57:56 +07:00
parent b68732f0c7
commit 3bbeea3682
7 changed files with 98 additions and 0 deletions

17
samples/Clojure/for.clj Normal file
View File

@@ -0,0 +1,17 @@
(defn prime? [n]
(not-any? zero? (map #(rem n %) (range 2 n))))
(range 3 33 2)
'(3 5 7 9 11 13 15 17 19 21 23 25 27 29 31)
;; :when continues through the collection even if some have the
;; condition evaluate to false, like filter
(for [x (range 3 33 2) :when (prime? x)]
x)
'(3 5 7 11 13 17 19 23 29 31)
;; :while stops at the first collection element that evaluates to
;; false, like take-while
(for [x (range 3 33 2) :while (prime? x)]
x)
'(3 5 7)

View File

@@ -0,0 +1,8 @@
[:html
[:head
[:meta {:charset "utf-8"}]
[:link {:rel "stylesheet" :href "css/bootstrap.min.css"}]
[:script {:src "app.js"}]]
[:body
[:div.nav
[:p "Hello world!"]]]]

View File

@@ -0,0 +1,13 @@
(defn into-array
([aseq]
(into-array nil aseq))
([type aseq]
(let [n (count aseq)
a (make-array n)]
(loop [aseq (seq aseq)
i 0]
(if (< i n)
(do
(aset a i (first aseq))
(recur (next aseq) (inc i)))
a)))))

View File

@@ -0,0 +1,15 @@
(defprotocol ISound (sound []))
(deftype Cat []
ISound
(sound [_] "Meow!"))
(deftype Dog []
ISound
(sound [_] "Woof!"))
(extend-type default
ISound
(sound [_] "... silence ..."))
(sound 1) ;; => "... silence ..."

View File

@@ -0,0 +1,5 @@
(defn rand
"Returns a random floating point number between 0 (inclusive) and
n (default 1) (exclusive)."
([] (scm* [n] (random-real)))
([n] (* (rand) n)))

20
samples/Clojure/svg.cljx Normal file
View File

@@ -0,0 +1,20 @@
^:clj (ns c2.svg
(:use [c2.core :only [unify]]
[c2.maths :only [Pi Tau radians-per-degree
sin cos mean]]))
^:cljs (ns c2.svg
(:use [c2.core :only [unify]]
[c2.maths :only [Pi Tau radians-per-degree
sin cos mean]])
(:require [c2.dom :as dom]))
;;Stub for float fn, which does not exist on cljs runtime
^:cljs (def float identity)
(defn ->xy
"Convert coordinates (potentially map of `{:x :y}`) to 2-vector."
[coordinates]
(cond
(and (vector? coordinates) (= 2 (count coordinates))) coordinates
(map? coordinates) [(:x coordinates) (:y coordinates)]))

View File

@@ -0,0 +1,20 @@
(deftest function-tests
(is (= 3
(count [1 2 3])))
(is (= false
(not true)))
(is (= true
(contains? {:foo 1 :bar 2} :foo)))
(is (= {"foo" 1, "baz" 3}
(select-keys {:foo 1 :bar 2 :baz 3} [:foo :baz])))
(is (= [1 2 3]
(vals {:foo 1 :bar 2 :baz 3})))
(is (= ["foo" "bar" "baz"]
(keys {:foo 1 :bar 2 :baz 3})))
(is (= [2 4 6]
(filter (fn [x] (=== (rem x 2) 0)) [1 2 3 4 5 6]))))