clojure-koans/src/koans/07_functions.clj

39 lines
955 B
Clojure
Raw Normal View History

(ns koans.07-functions
(:require [koan-engine.core :refer :all]))
2010-10-29 15:07:11 +00:00
(defn multiply-by-ten [n]
(* 10 n))
2010-02-09 04:57:08 +00:00
(defn square [n] (* n n))
2010-02-09 04:57:08 +00:00
(meditations
"Calling a function is like giving it a hug with parentheses"
2022-11-04 23:35:58 +00:00
(= 81 (square 9))
"Functions are usually defined before they are used"
2022-11-04 23:35:58 +00:00
(= 20 (multiply-by-ten 2))
2010-02-09 04:57:08 +00:00
"But they can also be defined inline"
2022-11-04 23:35:58 +00:00
(= 10 ((fn [n] (* 5 n)) 2))
2010-02-09 04:57:08 +00:00
"Or using an even shorter syntax"
2022-11-04 23:35:58 +00:00
(= 60 (#(* 15 %) 4))
2010-02-09 04:57:08 +00:00
"Even anonymous functions may take multiple arguments"
2022-11-04 23:35:58 +00:00
(= 15 (#(+ %1 %2 %3) 4 5 6))
2010-11-05 22:33:06 +00:00
"Arguments can also be skipped"
2022-11-04 23:35:58 +00:00
(= "AACC" (#(str "AA" %2) "bb" "CC"))
2010-05-07 02:56:43 +00:00
"One function can beget another"
2022-11-04 23:35:58 +00:00
(= 9 (((fn [] +)) 4 5))
"Functions can also take other functions as input"
2022-11-08 23:37:41 +00:00
(= 20 ((fn [f] (f 4 5)) *))
2010-02-09 04:57:08 +00:00
"Higher-order functions take function arguments"
2022-11-04 23:35:58 +00:00
(= 25 ((fn [f] (f 5)) (fn [n] (* n n))))
"But they are often better written using the names of functions"
2022-11-04 23:35:58 +00:00
(= 25 ((fn [f] (f 5)) square)))