Programming in Clojure (Part 2 Functions)

markm208

Mark Mahoney

Posted on April 18, 2021

Programming in Clojure (Part 2 Functions)

This post discusses creating functions in Clojure. Clojure is a functional programming language so this is a pretty important topic.

Functions

The first two programs show how to write functions in Clojure.

This program shows how to use a map to encapsulate data along with some functions that manipulate the data.

These programs show how to read and write to a file using functions.

Call to Action

Problem 1
Write three mathematical functions:

  • square() squares a passed in parameter
  • cube() cubes a passed in parameter
  • pow() raises a base number to an exponent

For this group of functions do not use any built in mathematical functions.

Hint: look at the Clojure function repeat() and reduce() for the pow() function. Use the let() function to hold temporary values so that they can be referred to later.

Problem 2
Write a function that takes a number and will calculate the factorial value for that number.

5! is 5 * 4 * 3 * 2 * 1 = 120

10! is 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 3,628,800

Hint: this type of problem is typically done with recursion but there is a simple way to do it without. Look at the range() and reduce() functions.

Problem 3
Write a function that determines whether a number is prime or not. Use the range() and filter() functions to filter out non-primes in a range of values.

Hint: look at the not-any?() and mod() functions for determining whether a number is prime or not.

Problem 4
Write a function that takes one or more string parameters, converts them to numbers, and then adds them together and returns the sum.

(println (add-strings "10")) ;prints 10
(println (add-strings "10" "20")) ;prints 30
(println (add-strings "10" "20" "30")) ;prints 60
(println (add-strings "10" "20" "30" "40")) ;prints 100
Enter fullscreen mode Exit fullscreen mode

Use Clojure's reduce() function or apply() to turn the strings into numbers and then add them together.

Comments and Feedback

You can find all of these code playbacks in my free 'book', An Animated Introduction to Clojure. I am always looking for feedback so please feel free to comment here or to send me a message. You can follow me on twitter @markm208.

💖 💪 🙅 🚩
markm208
Mark Mahoney

Posted on April 18, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related