Friday, September 04, 2020

#100DaysOfClojure (Day [5] Functions)

The excitement is building up, today I played with functions. A Clojure function has the following structure

(defn name params (body))

Here is a simple example of a Hello World function definition

(defn sayHello [toName] (println "Hello, " toName))

To call it looks like below with its output

(sayHello "Ahmed")

Hello,  Ahmed
=> nil

There are multi-arity functions which can take a different number of parameters so for example (indents and next line are for readable purposes only):

(defn saySomething 
    ([] (saySomething "Hello world!")) 
    ([msg] (println msg)))

;call the function
(saySomething)
Hello world!
=> nil

(saySomething "Goodbye")
Goodbye
=> nil
 
And there are Variadic Functions which may define a variable number of parameters, for example:

(defn sayManyThings [& thingsToSay] (println thingsToSay))
=> #'leinproj.core/sayManyThings

;call the function
(sayManyThings "Hello" "to" "Ahmed" "and" "friends")
(Hello to Ahmed and friends)
=> nil

There are a few more concepts with functions which I will continue with tomorrow

(println “Bye 4 Now!”) 

No comments: