June 22, 2014

Getting started with Clojure - Part 2

In this section, the main focus is on the different data types supported by Clojure. We also learn how to create and call functions.

Source : https://www.codeschool.com/code_tv/getting-started-with-clojure-part-2
  • 4. Literal Data Types
    • Built-in syntax for many data types
      • Strings - e.g "hello world", can have line breaks
      • Regular Expressions - e.g #"foo", java regular expressions
      • Numbers - Long (123), Hex (0x11), Floating point(123.24), Other bases (8r1234 for radix 8), Big Integer (1232131N), Big Decimal (231313.1232M), Ratios (11/3) 
      • Symbols/Keywords
        • symbols - foo (normal symbol) , bar/foo (symbol with a namespace) 
        • keywords - :foo (normal keyword) , com.test/foo (keyword with a namespace)
      • Vectors/Lists/Maps/Sets
        • Vector - sequence of values accessed by an index. similar to arrays. heterogenous (true to all 'collection' data types) 
          • [1 "two" [3.0 "four"]]
        • List - (1 "two" [3.0 "four"])
        • Map - dictionary type. has keys and values in pairs. use line break for readability. 
          • {"name" "RR" "age" 30}
          • {:name "RR" :birthday [01 01] [12 34] 97}
        • Set - #{1 2 3 "four"}
  • 5. Evaluation
    • Most things in Clojure evaluate to themselves - Numbers, String, Keywords, Maps/vectors/sets
    • Some things don't - Lists/Symbols
    • List evaluates to an invocation
      • First item is an operation, rest are arguments
      • evaluation is applied recursively 
      • e.g (+ 1 2 4),  (println "hello")
    • Defining functions
      • defined with "fn" operator 
      • arguments are listed in a vector
      • value of the last expression is the function return val 
        • e.g (fn [x y] (println x y) (+ x y))
        • to invoke the above ((fn [x y] (println x y) (+ x y)) 4 5) - the highlighted section being the function and the rest being arguments
  • 6. Naming things 
    • Use "def" operator to create a var
    • Vars associate symbols with values
    • Value of a symbol is the value of a var
    • e.g (def foo 3), (def bar [1 2 {:a 12}]
    • Naming a function
      • for the above function, (def add_nos (fn [x y] (println x y) (+ x y)))
      • to call the above (add_nos 4 5)
    • Easier way of naming a function 
      •  (defn add_nos [x y] (println x y) (+ x y))
      • the same var is defined for both -> #'user/add_nos

No comments:

Post a Comment