Skip to content

Instantly share code, notes, and snippets.

@bugra
Created February 8, 2014 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bugra/8884655 to your computer and use it in GitHub Desktop.
Save bugra/8884655 to your computer and use it in GitHub Desktop.
Clojure Learning
(ns tutorial.core)
(defn foo
"I don't do a whole lot."
[& args]
(concat args "Hello, World!"))
(foo "bugra")
; 1 + 2 + 3 + 4
(+ 1 2 3 4)
(* 1 2 3 4)
(+)
(*)
(first [1 2 3 4])
(last [1 2 3 4])
(first '(1 2 3 4))
1
"a string"
["internet" "is" "series" "of" "tubes"]
(str "To " "Be " "Or Not To Be")
(if true
"This is the string that is to be printed"
"This one does not get printed")
(if true
(do (println "Aww")
"what")
(do (println "Noo")
"no"))
(when true
"So Similar")
(def fruits
["apple"
"orange"
"strawberry"
"ananas"
"banana"])
(eval fruits)
(nil? 1)
(nil? nil)
(nil? 0)
(= 1 1)
(= nil nil)
(= false false)
(= true true)
(+ 1/5 2/3)
(+ 2.3 23)
(def name "Bugra")
(str "My name is " name)
(def my-map
{:a 1
:b "string"
:c []
:d {}
:plus +
:minus -
:first first
:last last
})
(get my-map :a)
((get my-map :plus) 1 2 3 4 5 6)
((get my-map :first) [23 2131 23 3])
(get my-map :division (str :division " does not exist"))
(get-in my-map [:c :d] "what")
(:d my-map)
(:c my-map)
(hash-map :python_like "dictionary" :interesting_access "True")
(get [3132 23123 213012] 1)
(get ["Vector's First Element" "Vector's Second Element" "Vector's Third Element"] 2)
(vector "a" "b" "b" "c")
(conj [1 2 3 ] 4)
(first '(1 2 3 4))
(nth '(2131 23 1 231 "str") 2)
;; Lists are different than vectors
(conj '(1 2 3 ) 4)
(def my-set #{"fruit" "apple" "what" 1 2 :keyword :a :b})
(conj my-set "fruit")
(conj my-set "orange")
(eval my-set)
(:a my-set)
(get my-set "fruit")
(set [1 1 2 3 5 8 8 8])
(get (set [1 2 3 4 5]) 3)
(hash-set 1 1 2 2 3 4 4)
(sorted-set :b :a :c :z :q :f :d :e)
(identity 'variable)
(def top9-movies
["The Shawshank Redemption"
"The Godfather" "The Godfather: Part II"
"The Dark Knight"
"Pulp Fiction"
"The Good, the Bad and the Ugly"
"Schindler's List"
"12 Angry Men"
"The Lord of the Rings: The Return of the King"
"Fight Club"])
(first top9-movies)
(second top9-movies)
(nth top9-movies 3)
(last top9-movies)
(eval top9-movies)
;(doc first)
;(source first)
((or + -) 1 2 3 4)
((or * /) 2 2 2 2)
((and (= 1 1) +) 1 2 3)
((first [+ 0]) 1 2 3)
(inc 1.1)
(map inc [0 1 2 3 4 5 6 7])
(reduce + [0 1 2 3 4 5 6 ])
(reduce * [1 2 3 4 5 6 7 8])
(reduce str [0 1 2 3 4 5 6])
; Map does not return a vector
; even though the input argument is a vector
; returns a lazy sequence
(type (map str [0 1 2 3 4 5 6 6]))
(map str [0 1 2 3 4 5 6])
(defn greetings
"This is the docstring of this function. I know
it is quite self explanatory"
[name]
(str "Greetings " name))
(greetings "Bugra")
(defn zero-parameter
"Zero parameter function"
[]
(str "Zero Parameters, None, Nada!"))
(defn one-parameter
"One parameter function"
[x]
(str "Only parameter is " x))
(defn two-parameters
"Two parameters function"
[x y ]
(str "Two parameters are " x " , " y))
(zero-parameter)
(one-parameter [1 2 3])
(two-parameters 10 20)
; Arity for default values for arguments
(defn summer
"This function sums"
([first-arg second-arg third-arg]
(vector (first first-arg) (first second-arg) (first third-arg)))
([first-arg second-arg]
(vector (first first-arg) (first second-arg) 0))
([first-arg]
(vector (first first-arg) 0 0))
([]
(vector 0 0 0)))
(def first-arg [1 2 3 4 5])
(def second-arg [213 231 123])
(def third-arg [21 231 0232 923])
(summer)
(summer first-arg)
(summer first-arg second-arg)
(summer first-arg second-arg third-arg)
(defn name-sentence
"Put your name in context!"
[name]
(str "Your name is " name))
(defn arity-example
"Different kind of arity"
[& names]
(map name-sentence names))
(arity-example "Clojure" "Python" "Java" "Scala")
; Rest params with normal params
(defn rest-params-normal-params
"Normal Parameters come first than rest of the params"
[name & things]
(str name " has favorite things: " (clojure.string/join ", " things)))
(rest-params-normal-params "Bugra" ["pen" "pencil" "computer"])
; Destructuring
(defn my-first
[[first-thing]]
first-thing)
(my-first ["bugra" "akyildiz" "python"])
(defn my-other-first
[first-thing]
(first first-thing))
(my-other-first ["bugra" "akyildiz" "python"])
(defn options
[[first-choice second-choice & other-choices]]
(println (str "First option: " first-choice))
(println (str "Second option: " second-choice))
(println (str "Other options are: "(clojure.string/join ", " other-choices))))
(options ["Clojure" "Java" "Scala" "Python"])
; Another Nice Destructuring
(defn name-age
;[{name :name age :age}] ; see the next line which corresponds to the same thing
[{:keys [name age]}]
(println age)
(str name " is " age " years old"))
(name-age {:name "Bugra" :age "24"})
(defn what-to-return
[]
(+ 1 2 3 4)
(*)
"what"
(map inc[1 2 3 4])) ; last form is returned
(what-to-return)
(defn divisible?
[number divider]
(zero? (rem number divider)))
(if (divisible? 100 10)
(str "100 is divisible by 10")
(str "100 is not divisible by 10"))
(map (fn [x](* x x)) [0 1 2 3 4 5])
(map (fn [x] (* x 3)) [5 125 15375])
(.toUpperCase "Bugra")
(.getName String)
; Anonymous functions could have names!
(def my-three-multiplier (fn [x] (* x 3)))
(my-three-multiplier 10)
; Shortcut for anonymous functions
(#(* % %) 9)
(#(* % %) 10)
(map #(str "My name is " %) ["Bugra" "Akyildiz"])
(#(str %2 " and " %1) "coffee" "bagel")
(#(identity %&) 1 "blarg" :type)
(defn inc-maker
[inc-by]
#(+ % inc-by))
(def inc3 (inc-maker 3))
(inc3 15)
(let [x 3]
x)
(let [b 3]
b)
(let [c [1 2 3 4 5]]
c)
(def dalmatian-list
["Pongo" "Perdita" "Puppy 1" "Puppy 2"])
(let [dalmatians (take 2 dalmatian-list)]
dalmatians)
(loop [iteration 0]
(println (str "Iteration is: " iteration))
(if (< iteration 3)
(recur (inc iteration))
(println "Iteration is done")))
; Regular Expressions
(defn has-matching-part?
[part]
(re-find #"^left-" (:name part)))
(has-matching-part? {:name "left-eye"})
(has-matching-part? {:name "blackbeard"})
(defn matching-part
[part]
{:name (clojure.string/replace (:name part) #"^left-" "right-")
:size (:size part)})
(matching-part {:name "left-eye" :size 1})
; Reduce
(reduce + 55 [11 12 13 14 15 16]) ; optional initial value
(reduce + [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16])
(map identity [:name "Bugra" "Akyildiz" "Glass"])
(seq {:name "Bugra" :occupation "Machine Learning Engineer"})
(filter neg? [0 1 2 -1 -2 3])
(filter pos? [0 1 2 -1 -12 132])
; Checking if the data structure is empty
(empty? [])
(empty? [1])
(empty? "")
(empty? '())
(empty? #{})
(empty? {})
(into {} (map identity {:sunglight-interaction "Glitter!"}))
(into [] (map identity [:garlic :tomato :cucumber]))
(into {:fruit "orange"} [[:vegetable "cucumber"]])
(conj [0] [1])
(into [0] [1]) ; that is what we want
(conj [0] 1) ; this is how we should write the combination if we want to have some meaningful result
(conj [0] 1 2 3 4 5)
(max [1 2 3 4])
(apply max [1 2 3 4])
(def mult10
(partial * 10))
(mult10 10)
(def my-pos? (complement neg?))
(my-pos? 1)
(filter my-pos? [1 2 3 -1 2 -231])
; Composition of the functions in a systematic way
; Ideal for pipeline
((comp clojure.string/lower-case clojure.string/trim) " UNCLEAN UGLy String ")
(+ 3 (+ 5 8))
(defn sleep-identity
[x]
(Thread/sleep 1000)
x)
(sleep-identity "Bugra")
(defn memoize-sleep-identity
[x]
(memoize sleep-identity))
;((memoize-sleep-identity "Bugra") "Bugra")
(def some-letters ["a" "b" "c" "d"])
(eval some-letters)
; List the namespaces that are available
(ns-name *ns*)
; List the available modules under the available namespaces
(ns-interns *ns*)
(get (ns-interns *ns*) 'some-letters)
(ns-map *ns*)
; To get the object in some space
; Note that this is also how we use some of the functions in the string
(deref #'tutorial.core/some-letters)
; To create a new namespace
; (create-ns)
; To switch a new namespace
; (in-ns)
; To implement private functions, we need to append the function name with "-"
; So that, the other namespaces cannot access to this function but only the namespace
; that the function resides in.
; To createa a new app, use the lein
; lein new app name-of-app
; When we create the app, the first file that it constructs is the core.clj
; This file is refererred as the project-name/core.clj for the project
;;;;;;;;;;;;;;;;;; DIRECTORY STRUCTURE ;;;;;;;;;;;;;;;;;;
; | .gitignore
; | doc
; | | intro.md
; | project.clj
; | README.md
; | resources
; | src
; | | the_divine_cheese_code
; | | | core.clj
; | test
; | | the_divine_cheese_code
; | | | core_test.clj
; import the tutorial.core module
(require 'tutorial.core)
; Main Method
(defn -main
[& args]
(println (some-letters)))
; To run the project
; From the main directory
; lein run
; to be able to module and refer it as a shortcut use this
; import module as shortcut => similar to python
(require '[tutorial.core :as core]) ; this is shorcut to the following
; is equivalent to the following
(require 'tutorial.core)
(alias 'core 'tutorial.core)
; Loading module, referring and using shortcut for its name;
(use '[tutorial.core :as core]); this is shortcut to the following
(require 'tutorial.core)
(refer 'tutorial.core)
(alias 'core 'tutorial.core)
; However, we __almost__ never use "use, require, alias and refer" but
; ns macro to load our modules
(ns tutorial.core
(:require [tutorial.core :as core]))
; We could require multiple modules from one project
;(ns tutorial.core
; (:require [tutorial.visualization.svg :as svg]
; [clojure.java.browse :as browse]))
(merge-with - {:age 25 :salary 78} {:age 24 :salary 72})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment