Hello ladies and gentlemen, Leo here. Today we will explore some Functional Programming in Swift.
Functional programming is a programming paradigm that has some really cool ideas. For example, functions are first-class citizens, which means that you can do everything you could do with any other type like Int, you can do with a function like passing as a parameter or putting in a variable.
Also, is where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that map values to other values, rather than a sequence of imperative statements which update the running state of the program.
The problem:
I have a dictionary representing a Shopping Cart. The cart dictionary structure is [Chocolate: Int] where chocolate is a class that has the name of the chocolate and its price, and the Int is the quantity of that item in the Shopping Cart. The problem is to sum the total cart value.
So here we have two separate problems. The first one we have to transform(map) into simple values and after that, we can sum them.
Let’s code!
Functional Programming and Swift – Solving the Problem
let cart = ShoppingCart.sharedCart.cart let total = cart.map { (key, value) in key.priceInDollars * Float(value) // 1 - here we are mapping each dictionary entry to a float value, and the result is a [Float] }.reduce(0, +) // 2 - after having the [Float] we can just simply apply a reduce function to sum them all
Explanation:
1 – The .map returns an array that each row that represents how much is the sum of the price of each item in the cart.
2 – The first parameter of reduction is the initial value, in this case, zero. The second is a function that will be used to reduce de values. In this case + in Swift is a function so we can pass by to sum all the elements and reduce to just ONE, the final sum result.
Done!
Any thoughts will be appreciated!
Algorithms: Continue Studying
Working with trees can be a really good challenge to test your recursive programming skills. This tree prunning problem is a great example of how to deal with recursive algorithms and tree data structures in Swift.
Trees are graphs, but not all graphs are trees and if you want to learn an A* algorithm to solve the eight puzzle children toy, you have it here. The A* is really good to find the fastest solutions but you will use a lot of memory in the process… or will you?
Summary
Today we learned how to solve the Shopping cart problem using only functional programming.
That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing!
You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.
Thanks for the reading and… That’s all folks.
Credits: image