user=> (+ 7654 1234)
8888
This page contains solutions to the "Test your knowledge" sections of the Learn Clojure guide.
Using the REPL, compute the sum of 7654 and 1234.
user=> (+ 7654 1234)
8888
Rewrite the following algebraic expression as a Clojure expression: ( 7 + 3 * 4 + 5 ) / 10
.
(/ (+ 7 (* 3 4) 5) 10)
Using REPL documentation functions, find the documentation for the rem and mod functions. Compare the results of the provided expressions based on the documentation.
user=> (doc rem)
clojure.core/rem
([num div])
remainder of dividing numerator by denominator.
nil
user=> (doc mod)
clojure.core/mod
([num div])
Modulus of num and div. Truncates toward negative infinity.
nil
Using find-doc, find the function that prints the stack trace of the most recent REPL exception.
pst
Define a function greet
that takes no arguments and prints "Hello".
(defn greet []
(println "Hello"))
Redefine greet using def
with fn
and #()
.
;; using fn
(def greet
(fn [] (println "Hello")))
;; using #()
(def greet
#(println "Hello"))
Define a function greeting
…
(defn greeting
([] (greeting "Hello" "World"))
([x] (greeting "Hello" x))
([x y] (str x ", " y "!")))
Define a function do-nothing
…
(defn do-nothing [x] x)
Define a function always-thing
…
(defn always-thing [& xs] 100)
Define a function make-thingy
…
(defn make-thingy [x]
(fn [& args] x))
Define a function triplicate
…
(defn triplicate [f]
(f) (f) (f))
Define a function opposite
…
(defn opposite [f]
(fn [& args] (not (apply f args))))
Define a function triplicate2
…
(defn triplicate2 [f & args]
(triplicate (fn [] (apply f args))))
Using the java.lang.Math
class …
user=> (Math/cos Math/PI)
-1.0
user=> (+ (Math/pow (Math/sin 0.2) 2)
(Math/pow (Math/cos 0.2) 2))
1.0
Define a function that takes an HTTP URL as a string…
(defn http-get [url]
(slurp
(.openStream
(java.net.URL. url))))
(defn http-get [url]
(slurp url))
Define a function one-less-arg
:
(defn one-less-arg [f x]
(fn [& args] (apply f x args)))
Define a function two-fns
:
(defn two-fns [f g]
(fn [x] (f (g x))))