About This

If all goes well, this will become a little online Clojure tutorial for the Facebook Clojure Community.

If it doesn't go well, blame me - my name is Carl Smotricz and I'm the only (so far) author.

I'm no Clojure guru. I'm an enthusiast looking to share my enthusiasm with others. Comments, suggestions, criticism, contributions are welcome.

4. Writing a Function

Typing expressions into the REPL is fine and good, but you can't become a famous Clojure programmer without writing functions.

Here's how to write a Clojure function "addit" that will add two numbers:

(defn addit [a b] (+ a b))

If we want to play with this function, we can just insert it into the code Nightcode auto-generates for us:


We want to Save and Build that, and if there's no error, we can Run with REPL:

Note: Running functions we define in code won't work in the REPL windows in the bottom left! The REPL there only knows the stuff already built into Clojure and its library.

In the window south of the main code window, Nightcode gives us a bit of explanation on how to work the REPL. Then it prompts us with the name of our namespace (I called the project function, so the namespace is function.core):

So then we can type in expressions, and they'll be evaluated in the namespace of our code, i.e. Clojure will know about addit, and this works:


So here's the assignment:

Write and test a function that will take three arguments a, b and c, and calculate
(b * c) - a
Hints:
  • A Clojure expression will accept an expression wherever it will accept a value; so you can nest expressions
  • The innermost (i.e. most deeply nested) expressions will be calculated first, and then evaluation goes outward from there.

No comments:

Post a Comment