Skip to content

Instantly share code, notes, and snippets.

@pholas
Created December 14, 2016 08:24
Show Gist options
  • Save pholas/37b421f4420925ff482e0aa31654ea89 to your computer and use it in GitHub Desktop.
Save pholas/37b421f4420925ff482e0aa31654ea89 to your computer and use it in GitHub Desktop.
clojure basics
;; (op parameter-1parameter-2 ….)
(* 1 2 3)
(+ 5 9 7)
(/ 4 5)
(- 2 3 4)
(map inc [1 2 3 4 5 6])
(defn some-function [times parameter]
"Prints a string certain number of times"
(dotimes [x times]
(println parameter)))
(some-function 3 "hello")
(defn hello
([] (hello "Clojure"))
([name] (str "Hello " name)))
(hello)
(def Scalars ["This is a string" ;; a simple string
"This is
a multiline
string" ;; a multiline string
true ;; Boolean true
false ;; Boolean false
\c ;; Character
\u0045 ;; Unicode char 45 E
:key ;; keyword
:sample
:some-keyword
42N ;;Big Integer
42 ;;long
0.1M ;;BigDecimal
22/7 ;; ratio
'some-name ;; symbol
nil ;; java null
#"\d" ;; regular expression.
])
(def collections [
'(1 2 3 4 5) ;; list
[1 2 3 4 5] ;; vector
#{1 2 3 4} ;; set
{:key 5 :key-2 "red"} ;; map
])
(import java.util.Date)
;; namespace
;; (ns ns-playground.hello)
;; (:require [some.package :refer [a-function another-function]])
(require '[clojure.java.io :as io])
(:require [some.package :refer :all])
(:import java.util.List)
(:import [java.util ArrayList HashMap])
;; interacting with java
(1 2 3 4 5)
(def a (new java.util.ArrayList 20))
(def a (ArrayList.))
;; (. instance method-name args*)
(. a add 5)
;; (.method-name instance args*)
(.add a 5)
;; Accessing inner classes
(java.util.AbstractMap$SimpleEntry. "key" "value") ;; note the $ sign
(java.util.Collections/emptyMap) ;; Calling a static method or function
(let [x 42]
(let [y (* x x)]
(println "x is " x)
(let [x 41]
(println "x is " x " and y " y))))
;; Sequential destructuring
(let [[f s] [1 2]] f) ;; 1
(let [[f s t] [1 2 3]] [f t]) ;; [1 3]
(let [[f] [1 2]] f);; 1
(let [[f s t] [1 2]] t);; nil
(let [[f & t] [1 2]] t);; (2)
(let [[f & t] [1 2 3]] t);; (2 3)
(let [[f & t] [1 2 3]] t);; (2 3)
(let [[f & [_ t]] [1 2 3]] [f t]);; [1 3]
;; Associative destructuring
(let [aaamap {:a 4 'a-value 5}]
(aaamap :a ))
(let [{a-value :a} {:a 5}] a-value) ;; 5
(let [{a-value :a c-value :c} {:a 5 :b 6 :c 7}] c-value) ;; 7
(let [{:keys [a c]} {:a 5 :b 6 :c 7}] c) ;; 7
(let [{:syms [a c]} {'a 5 :b 6 'c 7}] c) ;; 7
(let [{:strs [a c]} {:a 5 :b 6 :c 7 "a" 9}] [a c]) ;; [9 nil]
(let [{:strs [a c] :or {c 42}} {:a 5 :b 6 :c 7 "a" 9}] [a c]) ;; [9 42]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment