Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wuriyanto48/ab863cd17137b6b405837a2c8dccd301 to your computer and use it in GitHub Desktop.
Save wuriyanto48/ab863cd17137b6b405837a2c8dccd301 to your computer and use it in GitHub Desktop.
clojure higher-order functions clj 高阶函数
(meditations
"The map function relates a sequence to another"
(= [4 8 12] (map (fn [x] (* 4 x)) [1 2 3]))
"You may create that mapping"
(= [1 4 9 16 25] (map (fn [x] (* x x)) [1 2 3 4 5]))
"Or use the names of existing functions"
(= [false false true false false] (map nil? [:a :b nil :c :d]))
"A filter can be strong"
(= '() (filter (fn [x] false) '(:anything :goes :here)))
"Or very weak"
(= (list :anything :goes :here) (filter (fn [x] true) '(:anything :goes :here)))
"Or somewhere in between"
(= [10 20 30] (filter (fn [x] (< x 31)) [10 20 30 40 50 60 70 80]))
"Maps and filters may be combined"
(= [10 20 30] (map (fn [x] (* 10 x)) (filter (fn [x] (<= x 3)) [1 2 3 4 5 6 7 8])))
"Reducing can increase the result"
(= 24 (reduce (fn [a b] (* a b)) [1 2 3 4]))
"You can start somewhere else"
(= 2400 (reduce (fn [a b] (* a b)) (conj [1 2 3 4] 100)))
"Numbers are not the only things one can reduce"
(= "longest" (reduce (fn [a b]
(if (< 0 1) b a))
["which" "word" "is" "longest"])))

defined by wikipedia

is a function that does at least one of the following:

  • takes one or more functions as an input
  • outputs a function

Example

(defn twice [function x]
  (function(function x)))
 
(twice #(+ % 3) 7) ;13

higher-order functions in Clojure

  • map
  • reduce
  • partial
  • comp
  • complement
  • repeatedly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment