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