【clojure】02-clojure中的方法1

一、Clohjure常用方法

1.range

  • (range)
(range)
(0 1 2 3 4 5 6 7 8 9 10 ... 12770 12771 12772 12773 ... n)
  • (range end)

  • (range start end)

  • (range start end step)

    (take 4 (range)) ;  (0 1 2 3)
    

2.vec

  • (vec coll)

    转成数组[]

3.apply

  • (apply f args)
  • (apply f x args)
  • (apply f x y args)
  • (apply f x y z args)
  • (apply f a b c d & args)

如果你想在vector中找到最大值,需要使用apply

4、nthnext

  • (nthnext coll n)

取coll,从第n个之后的

5. take-nth

  • (take-nth n)
  • (take-nth n coll)

n 应该是几倍

Returns a lazy seq of every nth item in coll.  Returns a stateful
transducer when no collection is provided.
(take-nth 2 (range 10))
(0 2 4 6 8)

6. mod

  • (mod num div)

个人理解应该是求余 div对num求余

(mod 10 5) =>0

7.cons

list or vector
(cons 4 [1 2 3]) ; => (4 1 2 3)
(cons 4 '(1 2 3)) ; => (4 1 2 3)

8.conj

; Conj will add an item to a collection in the most efficient way.
; For lists, they insert at the beginning. For vectors, they insert at the end.
(conj [1 2 3] 4) ; => [1 2 3 4]
(conj '(1 2 3) 4) ; => (4 1 2 3)

9.concat

; Use concat to add lists or vectors together
(concat [1 2] '(3 4)) ; => (1 2 3 4)

10.map

; Use filter, map to interact with collections
(map inc [1 2 3]) ; => (2 3 4)

11.filter

; Use filter, map to interact with collections
(map inc [1 2 3]) ; => (2 3 4)
(filter even? [1 2 3]) ; => (2)

12.reduce

; Use reduce to reduce them
(reduce + [1 2 3 4])
; = (+ (+ (+ 1 2) 3) 4)
; => 10


; Reduce can take an initial-value argument too
(reduce conj [] '(3 2 1))
; = (conj (conj (conj [] 3) 2) 1)
; => [3 2 1]

13、function

; Use fn to create new functions. A function always returns
; its last statement.
(fn [] "Hello World") ; => fn

; (You need extra parens to call it)
((fn [] "Hello World")) ; => "Hello World"

; You can create a var using def
(def x 1)
x ; => 1

; Assign a function to a var
(def hello-world (fn [] "Hello World"))
(hello-world) ; => "Hello World"

; You can shorten this process by using defn
(defn hello-world [] "Hello World")

; The [] is the list of arguments for the function.
(defn hello [name]
  (str "Hello " name))
(hello "Steve") ; => "Hello Steve"

; You can also use this shorthand to create functions:
(def hello2 #(str "Hello " %1))
(hello2 "Julie") ; => "Hello Julie"

; You can have multi-variadic functions, too
(defn hello3
  ([] "Hello World")
  ([name] (str "Hello " name)))
(hello3 "Jake") ; => "Hello Jake"
(hello3) ; => "Hello World"

; Functions can pack extra arguments up in a seq for you
(defn count-args [& args]
  (str "You passed " (count args) " args: " args))
(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)"

; You can mix regular and packed arguments
(defn hello-count [name & args]
  (str "Hello " name ", you passed " (count args) " extra args"))
(hello-count "Finn" 1 2 3)
; => "Hello Finn, you passed 3 extra args"

14、Maps

; Maps
;;;;;;;;;;

; Hash maps and array maps share an interface. Hash maps have faster lookups
; but don't retain key order.
(class {
    
    :a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap
(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap

; Arraymaps will automatically become hashmaps through most operations
; if they get big enough, so you don't need to worry.

; Maps can use any hashable type as a key, but usually keywords are best
; Keywords are like strings with some efficiency bonuses
(class :a) ; => clojure.lang.Keyword

(def stringmap {
    
    "a" 1, "b" 2, "c" 3})
stringmap  ; => {"a" 1, "b" 2, "c" 3}

(def keymap {
    
    :a 1, :b 2, :c 3})
keymap ; => {:a 1, :c 3, :b 2}

; By the way, commas are always treated as whitespace and do nothing.

15、根据键获得值

(stringmap "a") ; => 1
(keymap :a) ; => 1

; Keywords can be used to retrieve their value from a map, too!
(:b keymap) ; => 2

; Don't try this with strings.
;("a" stringmap)
; => Exception: java.lang.String cannot be cast to clojure.lang.IFn

; Retrieving a non-present key returns nil
(stringmap "d") ; => nil

16、assoc \dissoc

; Use assoc to add new keys to hash-maps
(def newkeymap (assoc keymap :d 4))
newkeymap ; => {:a 1, :b 2, :c 3, :d 4}

; But remember, clojure types are immutable!
keymap ; => {:a 1, :b 2, :c 3}

; Use dissoc to remove keys
(dissoc keymap :a :b) ; => {:c 3}

17、Sets

(class #{
    
    1 2 3}) ; => clojure.lang.PersistentHashSet
(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3}

; Add a member with conj
(conj #{
    
    1 2 3} 4) ; => #{1 2 3 4}

; Remove one with disj
(disj #{
    
    1 2 3} 1) ; => #{2 3}

; Test for existence by using the set as a function:
(#{
    
    1 2 3} 1) ; => 1
(#{
    
    1 2 3} 4) ; => nil

18、if

; Logic constructs in clojure are just macros, and look like
; everything else
(if false "a" "b") ; => "b"
(if false "a") ; => nil

19、条件

; Use let to create temporary bindings
(let [a 1 b 2]
  (> a b)) ; => false

20、do

; Group statements together with do
(do
  (print "Hello")
  "World") ; => "World" (prints "Hello")

21、defn和let

; Functions have an implicit do
(defn print-and-say-hello [name]
  (print "Saying hello to " name)
  (str "Hello " name))
(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff")

; So does let
(let [name "Urkel"]
  (print "Saying hello to " name)
  (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel")

22、->

; Use the threading macros (-> and ->>) to express transformations of
; data more clearly.

; The "Thread-first" macro (->) inserts into each form the result of
; the previous, as the first argument (second item)
(->  
   {
    
    :a 1 :b 2} 
   (assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3)
   (dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b)

22、->>

; This expression could be written as:
; (dissoc (assoc {:a 1 :b 2} :c 3) :b)
; and evaluates to {:a 1 :c 3}

; The double arrow does the same thing, but inserts the result of
; each line at the *end* of the form. This is useful for collection
; operations in particular:
(->>
   (range 10)
   (map inc)     ;=> (map inc (range 10)
   (filter odd?) ;=> (filter odd? (map inc (range 10))
   (into []))    ;=> (into [] (filter odd? (map inc (range 10)))
                 ; Result: [1 3 5 7 9]

23、as->

; When you are in a situation where you want more freedom as where to
; put the result of previous data transformations in an 
; expression, you can use the as-> macro. With it, you can assign a
; specific name to transformations' output and use it as a
; placeholder in your chained expressions:

(as-> [1 2 3] input
  (map inc input);=> You can use last transform's output at the last position
  (nth input 2) ;=>  and at the second position, in the same expression
  (conj [4 5 6] input 8 9 10)) ;=> or in the middle !
                               ; Result: [4 5 6 4 8 9 10]

24、atom

; STM
;;;;;;;;;;;;;;;;;

; Software Transactional Memory is the mechanism clojure uses to handle
; persistent state. There are a few constructs in clojure that use this.

; An atom is the simplest. Pass it an initial value
(def my-atom (atom {
    
    }))

; Update an atom with swap!.
; swap! takes a function and calls it with the current value of the atom
; as the first argument, and any trailing arguments as the second
(swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1)
(swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2)

; Use '@' to dereference the atom and get the value
my-atom  ;=> Atom<#...> (Returns the Atom object)
@my-atom ; => {:a 1 :b 2}

; Here's a simple counter using an atom
(def counter (atom 0))
(defn inc-counter []
  (swap! counter inc))

(inc-counter)
(inc-counter)
(inc-counter)
(inc-counter)
(inc-counter)

@counter ; => 5

; Other STM constructs are refs and agents.
; Refs: http://clojure.org/refs
; Agents: http://clojure.org/agents

https://zhuanlan.zhihu.com/p/640367279

25、constantly

(constantly x)
;;Returns a function that takes any number of arguments and returns x.
;;返回一个接收任意参数并返回x的函数
user=> (def boring (constantly 10))
#'user/boring

user=> (boring 1 2 3)
10

user=> (boring)
10

user=> (boring "Is anybody home?")
10

26、or

  • or)
  • (or x)
  • (or x & next)
user> (or true false false)
true

user> (or true true true)
true

user> (or false false false)
false

user> (or nil nil)
nil

user> (or false nil)
nil

user> (or true nil)
true

;; or doesn't evaluate if the first value is true
user> (or true (println "foo"))
true

;; order matters
user> (or (println "foo") true)
foo
true

;; does not coerce a given value to a boolean true, returns the value
user> (or false 42)
42

user> (or false 42 9999)
42

user> (or 42 9999)
42

猜你喜欢

转载自blog.csdn.net/liqiannan8023/article/details/132647621