Skip to content

Commit 13c3994

Browse files
committed
add lab solutions at end of functions section
1 parent 75fac41 commit 13c3994

File tree

1 file changed

+128
-0
lines changed

1 file changed

+128
-0
lines changed

src/cljlab/functions.clj

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,134 @@ vector
548548
___)
549549
;; @@
550550

551+
;; **
552+
;;; # Lab Solutions
553+
;;;
554+
;;; **Note:** All lab solutions are in the section following this one if you want to check your answers!
555+
;;;
556+
;;; ### Defining a function
557+
;; **
558+
559+
;; @@
560+
(defn greet []
561+
(println "Hello"))
562+
;; @@
563+
564+
;; **
565+
;;; ### Different ways to define functions
566+
;; **
567+
568+
;; @@
569+
(def greet (fn [] (println "Hello")))
570+
571+
(def greet #(println "Hello"))
572+
;; @@
573+
574+
;; **
575+
;;; ### Arities with defaults
576+
;; **
577+
578+
;; @@
579+
(defn greeting
580+
([] (greeting "Hello" "World"))
581+
([x] (greeting "Hello" x))
582+
([x y] (str x ", " y "!")))
583+
;; @@
584+
585+
;; **
586+
;;; ### Do nothing
587+
;; **
588+
589+
;; @@
590+
(defn do-nothing [x] x)
591+
;; @@
592+
593+
;; **
594+
;;; ### Do one thing well
595+
;;;
596+
;;;
597+
;; **
598+
599+
;; @@
600+
(defn always-thing [& args] :thing)
601+
;; @@
602+
603+
;; **
604+
;;; ### Do many things
605+
;; **
606+
607+
;; @@
608+
(defn make-thingy [x]
609+
(fn [& args] x))
610+
;; @@
611+
612+
;; **
613+
;;; ### In triplicate
614+
;; **
615+
616+
;; @@
617+
(defn triplicate [f]
618+
(f) (f) (f))
619+
;; @@
620+
621+
;; **
622+
;;; ### Do the opposite
623+
;; **
624+
625+
;; @@
626+
(defn opposite [f]
627+
(fn [& args] (not (apply f args))))
628+
;; @@
629+
630+
;; **
631+
;;; ### In triplicate redux
632+
;; **
633+
634+
;; @@
635+
(defn triplicate2 [f & args]
636+
(triplicate (fn [] (apply f args))))
637+
;; @@
638+
639+
;; **
640+
;;; ### Squaring the circle
641+
;; **
642+
643+
;; @@
644+
(Math/cos Math/PI)
645+
;;=> -1.0
646+
647+
(+ (Math/pow (Math/sin Math/PI) 2)
648+
(Math/pow (Math/cos Math/PI) 2))
649+
;;=> 1.0
650+
;; @@
651+
652+
;; **
653+
;;; ### Go fetch
654+
;; **
655+
656+
;; @@
657+
(defn http-get [url]
658+
(slurp (.openStream (java.net.URL. url))))
659+
;; @@
660+
661+
;; **
662+
;;; ### Partial function application
663+
;; **
664+
665+
;; @@
666+
(defn one-less-arg [f x]
667+
(fn [& args] (apply f x args)))
668+
;; @@
669+
670+
;; **
671+
;;; ### Function composition
672+
;; **
673+
674+
;; @@
675+
(defn two-fns [f g]
676+
(fn [x] (f (g x))))
677+
;; @@
678+
551679
;; **
552680
;;;
553681
;;; ## Navigation

0 commit comments

Comments
 (0)