Created
February 11, 2018 16:41
-
-
Save furio/48bfee6d6cf1da84885538bef929c06d to your computer and use it in GitHub Desktop.
Clojure functions exercises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; https://clojure.org/guides/learn/functions#_test_your_knowledge | |
; defn | |
(defn greet [] (println "Hello")) | |
; def fn | |
(def greet (fn [] (println "Hello"))) | |
; def with # | |
(def greet #(println "Hello")) | |
; (greet) | |
;;;;;;;;; | |
(defn greeting | |
([] (greeting "World")) | |
([x] (greeting "Hello" x)) | |
([x y] (str x ", " y "!")) | |
) | |
;; For testing | |
(assert (= "Hello, World!" (greeting))) | |
(assert (= "Hello, Clojure!" (greeting "Clojure"))) | |
(assert (= "Good morning, Clojure!" (greeting "Good morning" "Clojure"))) | |
;;;; | |
(defn do-nothing [x] (identity x)) | |
(do-nothing 2) | |
;;; | |
(defn always-thing [& y] (identity :thing)) | |
(always-thing 1 2 3 4 5) | |
;;; | |
(defn make-thingy [x] (fn [& this] (identity x))) | |
;; Tests | |
(let [n (rand-int Integer/MAX_VALUE) | |
f (make-thingy n)] | |
(assert (= n (f))) | |
(assert (= n (f :foo))) | |
(assert (= n (apply f :foo (range))))) | |
;; | |
(defn triplicate [f] (dotimes [x 3] (apply f []))) | |
;; | |
(defn opposite [f] | |
(fn [& args] (not (apply f args)))) | |
;; | |
(defn triplicate2 [f & args] | |
(triplicate (fn [] (apply f args)))) | |
(triplicate2 println "Hello") | |
;; | |
(assert (= (Math/cos Math/PI) -1.0)) | |
(let [n (rand-int Integer/MAX_VALUE)] | |
(assert (= (+ (Math/pow (Math/sin n) 2) (Math/pow (Math/cos n) 2) ) 1.0)) | |
) | |
;; | |
(defn http-get [url] | |
(let [jurl (java.net.URL. url)] | |
(slurp (.openStream jurl)) | |
) | |
) | |
(assert (.contains (http-get "http://www.w3.org") "html")) | |
;; | |
(defn one-less-arg [f x] | |
(fn [& args] (apply f x args))) | |
;; | |
(defn two-fns [f g] | |
(fn [x] (f (g x))) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment