Category Archives: Functional Programming

What’s an Object?

I was editing my interview with Orta Therox yesterday when I realized I mentioned asking my boss Brad Larson what an object was.

I realized when listening to this that I hadn’t given any context because I wasn’t anticipating talking about that during the interview and I come off being rather ignorant in the course of this question. So, to avoid having to turn in my nerd card, I am going to give some context and give a more nuanced explanation behind that question.

My Personal Background with Object-Oriented Programming

I started going to school in 2010 for computer programming. I was 28 and I had almost no experience whatsoever with computer programming. My background was writing HTML when I was in high school and learning how to compile “Hello, world!” in Perl. At the time I enrolled I was working at Target because I failed to find a journalism job after I graduated and I really didn’t want to work at Target for the rest of my life. Programming seemed like it would be a good fit and it didn’t seem like it was going anywhere for a while.

I got through my first semester of introductory programming okay. Starting in your second semester, you had to pick a language to study for the next three semesters. At the time I was making this decision, there were three languages to pick from: Java, PHP, and VB.Net. I decided I would pick whichever one fit into my work schedule. The one that fit was VB.Net.

Our introductory class kept getting further and further behind. By the time we got to the end of the semester, we had never spoking about object-oriented programming. It was something we were supposed to do, but we just never got around to it.

The following fall, I took the advanced class. It was a night class, which I don’t really do well with anyway. The first class period, my teacher showed me object-oriented programming for the first time. I had no idea what the fuck he was talking about.

A bunch of code was in other files! How did it work together? How does the computer know to look in these other files?? Wait, what the hell is polymorphism? Am I having a bad acid trip??

After three hours of this, the teacher said since this was all review he was never going to go over any of this ever again. That was when I realized I was kind of screwed.

I decided to drop out after I asked what a constructor was and the teacher asked me if I learned anything the previous semester. At this point I had a decent job with people that I liked. I figured I was too stupid to learn programming because I wasn’t born with an intuitive sense for it and I was tired of feeling stupid all the time.

Six months after this, I took a new job that was the most miserable job I have ever had. The plus side to this job was that I taught myself programming while I was there. I realized I hadn’t put enough effort into it and if I just programmed forty hours a week I could learn it. So I went back to school.

I finally grokked OOP when I took the Intro to Java class. They introduced objects immediately and forced you to use them throughout the whole semester so you could get used to them. I started to understand about file paths and how the program knew how to find your other classes and how you imported them and how you constructed them. I felt like after I understood this for the first time that I was a “real” programmer. I hadn’t felt that way before grasping object orientation.

OOP is Not the Only Paradigm

I went from Java to iOS/Cocoa/Objective-C programming. I had a few vague issues when I was learning Objective-C with trying to pass around things that weren’t objects. Rather than really think about it at the time, I just got annoyed and turned all of my ints and floats into NSNumber objects to shut up the compiler.

Here is a sample header file you might commonly make if you were creating an Objective-C project:

@interface MyViewController ()
 
@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic, strong) UIImageView *blurredImageView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) CGFloat screenHeight;
 
@end

In my experience with Objective-C, everything was an object. You created classes, which were objects, and you populated them with instances of other objects and in turn instantiated your new object in instances of UIViewController objects.

You had header and implementation files. The name of your class was the same as the name of your implementation file. Every file has a class. This is what programming is. It’s objects all the way down.

My first experience with understanding that this wasn’t the only way of doing things came several months ago. I was working on translating a plug-in we were using to a piece of code we kept internally. I had a weird method I was dealing with that wouldn’t compile.

After fighting with it for a while, I took it to Brad and asked him what I was doing wrong. He told me I was treating the function like a method. This statement kind of blew my mind because I thought that methods and functions were the same thing. I thought we called functions methods in Objective-C the same way that Java interfaces were the same thing as Objective-C protocols. (Yes, I am aware I am probably wrong about this as well. I am still learning.)

I didn’t know that there was a difference in Objective-C between functions and methods. Functions exist outside of classes and methods are functions that are embedded in a class. I hadn’t really thought about this or why anyone would want to do that. I simply assumed that all functions were methods and everything had to be encapsulated in a class.

This was only the tip of the iceberg.

Becoming Functional

Back in November, Brad went away for a week for a trade show. We were planning to rewrite all of our control software in Swift and he wanted me to take a look at the code he had written so far to make sure that I understood it.

What I saw completely broke my reality.

He has posted a sample project on GitHub including some of the code I looked at initially. Here is a small sample of what I saw that changed the way I think about programming:


import Foundation

// MARK: -
// MARK: Error protocols

public protocol ErrorType {}

protocol PresentableError {
    var errorTitle: String { get }
    var errorInfo: String { get }
}

// MARK: -
// MARK: Error types

enum CommunicationsError: ErrorType, Printable, Equatable {
    case ReadWriteTimeout
    case WrongByteCount(expectedByteCount:UInt, receivedByteCount:UInt)
    case CorruptedResponse(expectedResponse:[UInt8], receivedResponse:[UInt8])
    
    var description : String {
        get {
            switch (self) {
                case .ReadWriteTimeout: return ".ReadWriteTimeout"
                case let .WrongByteCount(expectedByteCount, receivedByteCount): return ".WrongByteCount(expectedByteCount:\(expectedByteCount), receivedByteCount:\(receivedByteCount)"
                case let .CorruptedResponse(expectedResponse, receivedResponse): return ".CorruptedResponse(expectedResponse:\(expectedResponse), receivedResponse:\(receivedResponse)"
            }
        }
    }
}

enum ElectronicsError: ErrorType, Printable, Equatable {
    case ElectronicsDisconnected
    case UnrecoverableCommunicationNoise
    
    var description : String {
        get {
            switch (self) {
                case .ElectronicsDisconnected: return ".ElectronicsDisconnected"
                case .UnrecoverableCommunicationNoise: return ".UnrecoverableCommunicationNoise"
            }
        }
    }
}

// MARK: -
// MARK: Equatable protocol compliance for these errors

func == (lhs: CommunicationsError, rhs: CommunicationsError) -> Bool {
    switch (lhs, rhs) {
        case let (.ReadWriteTimeout, .ReadWriteTimeout): return true
        case let (.ReadWriteTimeout, _): return false
        case let (.WrongByteCount(expectedByteCount, receivedByteCount), .WrongByteCount(expectedByteCount2, receivedByteCount2)):  return ((expectedByteCount == expectedByteCount2) && (receivedByteCount == receivedByteCount2))
        case let (.WrongByteCount, _): return false
        case let (.CorruptedResponse(expectedResponse, receivedResponse), .CorruptedResponse(expectedResponse2, receivedResponse2)): return (equal(expectedResponse, expectedResponse2) && equal(receivedResponse, receivedResponse2))
        case let (.CorruptedResponse, _): return false
    }
}

func == (lhs: ElectronicsError, rhs: ElectronicsError) -> Bool {
    switch (lhs, rhs) {
        case (.ElectronicsDisconnected, .ElectronicsDisconnected): return true
        case (.ElectronicsDisconnected, _): return false
        case (.UnrecoverableCommunicationNoise, .UnrecoverableCommunicationNoise): return true
        case (.UnrecoverableCommunicationNoise, _): return false
    }
}

The name of this file is ErrorTypes.swift. There is no ErrorTypes class. There is nothing in this file named ErrorTypes.

NOTHING IN THIS FILE IS AN OBJECT!!

We have several enums, which are not objects, that we are references for type conformity. We have UInts, which are not objects. We also have functions. Lots and lots of functions. That aren’t associated with a class. They’re just out there like llamas roaming free.

When I tried to understand this I felt like I went to a party and someone asked if I wanted to use another person’s liver. I didn’t know if was possible to call functions that were not associated with a class instance. I had never seen anything like this before. I couldn’t believe this would build and run and compile just fine. I felt like I fell down a rabbit hole and nothing made sense anymore.

Reorienting Myself with Reality

I, like many people, learned programming in the age of Imperative Programming. Java has been around for twenty years and many people learned programming with Java. A lot of us don’t know anything except the Object Oriented way of doing things. To many of us, this is what programming is.

It doesn’t have to be.

One reason I am so vocal in my defense of Swift is because this realization has completely changed my reality. I used to think there was only one way of doing things. Well, I won’t say that. There was one right way of doing things and then there was the “Dear god, what is this person thinking by having this property controlled in four different places?!” way of doing things.

Being exposed to Swift and seeing that you don’t have to put everything in a class has been a revelatory experience for me. It is forcing me to reevaluate everything I know about programming.

I never thought about what an object was before because there was no point because everything was an object. Now, I am trying to get a better understanding of what an object actually is. I wrote about the difference between structs and classes and at the time I really didn’t understand why you would want to use a struct instead of a class if they essentially do the same things. I now understand that you want to try to use structs when possible because they aren’t objects. Objects come with a lot of overhead. They let you do some more powerful things like subclassing through polymorphism, but you don’t always need to do those things. Looking at how powerful the enums are that Brad uses in his code, I am fascinated by how confined my own view was when I thought everything had to be an object and exist in a class.

So yes, I did ask what an object is. I know most programmers worth their salt can tell you the definition of what an object is, but I don’t think many of them stop to think about why we use them and if they are the best way of doing things. Or if they bother to wonder if objects are the only way of doing things.

Functional Programming in Swift: Chapter 3 – Wrapping Core Image

**Note- I originally took this post down because I wasn’t really happy with how I organized it. I also believe that this series has a larger readership than I originally envisioned and I felt that the assumptions I made about this post were confusing. I am going to repost this post and figure out how to proceed in a way that is useful to everyone who is reading my blog. **

I am writing a series of blog posts analyzing the code and concepts from each chapter in Functional Programming in Swift. I am assuming if you are reading this that you are following along in the book, so I am not references their specific code snippets in my blog.

The purpose of this chapter is to show the reader how to do a very important thing in programming, which is wrap a framework or an API written in another language, such as C.

Being able to integrate lower level code into your applications is a really important skill to be able to master. Over the last month I have had a project where I had to write a few wrapper classes around XML-parsing functionality in the C library libxml2, which I will write about in a later blog post. Learning how to search the sparse documentation for this library and figuring out how to integrate it with Swift was a really interesting and painful learning experience. Even though a lot of times I wanted to hang my head and weep in despair, after I got it working I felt kind of like one of those douchebag programming ninjas that recruiters keep contacting me looking for.

This might not be the best sales pitch for why you should care about this stuff, so without further adieu, I will get to the content.

Core Image

Even though the focus of this chapter wasn’t specifically on learning Core Image, I wanted to take a moment to talk about it because it’s a neat little framework.

Core Image is a framework that allows you to add filters to photos in both iOS and Mac applications. Core Image is very similar to GPUImage, except GPUImage is open source, so you can go in and actually see how all of the shaders were written. Core Image has a few more filters than GPUImage has. In iOS 8, Apple opened up the ability for you to write your own Core Image filters, which wasn’t possible before.

Core Image is, as my coauthor Chris Adamson calls it, “stringly typed.” If you want to use a filter from Core Image, you have to reference it in a string. If you spell the filter name wrong then your project will fail silently. Whereas you can use auto-complete on other parts of your project to ensure that you don’t get felled by spelling errors, there is alas no auto-complete in Core Image.

If you’re interested in how to write shaders for either Core Image or GPUImage, I recently wrote an article about it for Objc-io. There are a lot of other neat photo articles in this issue too, so be sure to go check it out if you want to know more about how to use photos in your iOS/Mac applications.

But enough of my own buzz marketing, on to the actual content of the chapter…

Wrapper Type

Generally speaking, Core Image has a rather repetitive pattern. You take an image, filter it, then you take that result and feed it to the next filter you are using.

If you’ve ever used Core Animation or another framework that affects the output of what goes on your screen, you will know that the order you implement your changes in affects your output. The same thing goes for your image filters. If you add more than one filter to an image, changing the order will change what the output image looks like.

Since you are using a filter chain where you are taking the output of one operation as the input of another, it makes sense to encapsulate this functionality into its own type. In this case, the type is a function that takes a CIImage and returns a CIImage.

CIImage filters all take different types of parameters. Some filters only take an image as a parameter while other ones many more. We want to be able to customize our filter functions to take the correct number of parameters. Regardless of what kind of filter we are making or how many parameters they take, we want each of our new custom filter functions to return a function that conforms to the Filter type alias. Naming this function type makes our code cleaner and safer by assigning a name to it and removing code we would have to write over and over again.

Convenience Initializers and Computed Properties

We want to make it easier to extract the output image so that we can chain this filter’s output image to the input of the next instance of our CIFilter class. We are using a convenience initializer and a computed property to extend the class to customize it for our needs.

The class extension has three pieces we are going to look at: a convenience initializer, a computed property, and a typealias representing a dictionary that holds our Core Image parameters.

Any time we create an instance of a class or a struct, we have to handle initializing it. Back in Objective-C we had our pattern of [[NSString alloc] init] to initialize our instances. We still have to initialize our instances, but like many thing in Swift, this process has been simplified. Instead of the long, verbose way of initialization, we just use “()”, which is a void function call. This initialization function is void by default, but life wouldn’t be very interesting if we couldn’t customize things to suit our needs.

Just because the default initializer is a void function does not mean that it always must be. If we have want to pass in parameters to the initializer, we can do so. In the example used in this chapter, we are trying to customize the CIFilter class. We are doing that by extending the class to include the functionality we need.

The normal CIFilter initializer just takes the name of the filter being used. We want to initialize the filter with the dictionary of parameters along with the name. In order to make it easier and clearer what we are doing, we are typealiasing the dictionary of parameters and passing that type into our convenience initializer. Within the convenience initializer, we are calling CIFilter’s designated initializer, essentially wrapping the base CIFilter initialization within another function that allows us to do more.

The last piece of our extension is a computed property, which is our coveted output image. We are treating an outputImage property that is of type CIImage and instead of just setting it to a CIImage, we are checking the value for the key that we are using (which in this case is the name for the CIFilter we want to use) and returning a CIImage.

Computed properties are interesting. They do not store a value. Instead, they are a getter to find and set properties and values indirectly. It is my impression (which, if wrong, I would really appreciate someone correcting for me) that they are similar to functions but with slightly less overhead. Natasha The Robot says in this post that a computed property is a function disguised as a property. I am on the fence about what the difference is between a function and a computed property, so I am on the fence about how to handle them. Would like to write about them further in a future blog post, so hit me up with any thoughts you have at some point in time.

Compositing Filters

Anyone familiar with special effects or Photoshop might be familiar with compositing. Compositing is the art of layering multiple images and filters together to create a single new image. Compositing encompasses everything from making collages out of multiple images to generating large Photoshop pieces of art that have hundreds of layers.

The way we are using compositing here is that we are taking several simple image filters and we are combining them together to make a larger, more complex image filter. Many of the large, complex image filters in both Core Image and GPUImage are composites of smaller, simpler filters.

Core Image has an entire section of filters that are exclusively used to composite images. If you have a chance, it’s a lot of fun to play with compositing filters. If you work with Photoshop and you’re familiar with the various blend modes, these are represented in this category of Core Image filter. You can get some really awesome effects using compositing and blend modes in your photography and I encourage you to explore them.

The first composite filter we are creating is one that superimposes a color on top of the original image. It is made up of the CIConstantColorGenerator and CISourceOverCompositing. The Color Generator is just creating a blanket color layer whose output is not at all affected by the underlying image. The Source Over Compositing is simply taking one image and placing them over another. In our case, it is placing the Color Generator layer on top of our image we want to filter.

After we create this composite filter, we are chaining it to the output of the blur filter. So, first we are taking our image, applying the blur filter, then taking the output from the blur filter and applying our composited red filter to the top. We are specifying that the opacity on the red filter is only twenty percent so that the the second filter doesn’t completely block out the first filter or the input image.

Adding Functionality

Since being able to compose two or more filters together is an incredibly useful thing to be able to do and something we might need to do many times, it makes sense to write a custom function to simplify this process. Also, considering the number of inputs we are dealing with for this functionality, being able to simplify the code and avoid missed parens is a good use of our time.

The composeFilters() function being defined takes two filters as parameters and returns a new filter. In the code sample, we see that we are setting a variable to hold the output of this function, which is a filter. We are then creating a second variable that will hold the output of the filter we just created. Since the output from the composeFilters function is a filter, when you use the variable you are calling a Core Image function that is filtering the image being used as a parameter. When I read through this at first, it took me a little bit to parse apart the logic.

Infix Operators

Infix, Postfix, and Prefix notation is a complex way of labeling a phenomenon most programmers are familiar with: Where to place an operator.

Infix operators are placed between two operands. Which is an obtuse way of saying you write an equation like this:

X + Y

The operator, in this case the “+” sign, gets placed “in-between” the numbers it is operating on.

Prefix operators are placed, just as they sound, before the operands:

+XY

I’ll bet you can figure out how to write a postfix operator now:

XY+

What do these operators do? Why are there a bunch of them?

Think back to your Algebra class. Remember PEMDAS? That acronym helps us remember the order of operations. If you want to isolate two numbers that you want to add together before the result is multiplied, you had to put parentheses around them to ensure that the product was calculated, not just the first number. Infix, Prefix, and Postfix operators affect the order of operations in mathematical calculations. All equations can be represented and translated in each style, so theoretically you don’t lose any functionality by not understanding how to use each type of operator.

These operators are incredibly common in mathematics. Since Haskell and other functional languages evolved from Lambda Calculus, there are a lot of operators and notations that are foreign and unfamiliar to people like me who flunked calculus and grew up on imperative programming.

Swift lets you write your own custom operators. There is a list of ASCII characters that can be used to write custom operators. You have to specify what type of operator you are defining. If you are defining an infix operator, as we are doing here, you need to specify the direction of associativity. In standard mathematical equations we have associativity from left to right. You can choose left, right, or none. None, which is the default, means that you can’t place your custom operator next to another operator with the same precedence.

I am still trying to figure this part of the chapter out. I don’t know why the custom operator “>>>” was chosen. I don’t know if the character is significant or important. My understanding of the code as written is that instead of using a text label for our composeFilters function, we are using symbols. I know this is a common thing in languages like Haskell and unfortunately I haven’t delved into them enough to be able to fully answer my own questions about how infix operators are being utilized here. Again, if someone has an answer, I would appreciate a ping on Twitter.

Currying

Currying is the process of taking one function that takes multiple parameters and breaking it down into a sequence of functions that each take a single argument. For example, if you were writing a function that took two floats as a length and a width for a rectangle, you could rewrite this function to take the first parameter and then evaluates a sequence of functions, each of which take one parameter.

Currying is found in languages like Haskell. In Haskell, the language only allows you to pass one parameter into a function. Currying is a way to get around this constraint.

Side note: Both Haskell and curried functions are named for Haskell Curry. Curry was a mathematician and logician who hopefully didn’t get his lunch money stolen too often for having such a strange name.

Currying gives us some options for customizing our functions. Currying allows us to seed functions by supplying too few arguments and using it as a basis for fully implementing another function. It allows us to choose if we want to apply the function to all of our parameters.

Since this post is getting rather long, I don’t really want to write a comprehensive explanation of currying and why you want to use it. I will save that for another post. The concept of currying is introduced in this chapter, so I wanted to cover it just a little. I would also like to look over the code from this chapter to get a better grasp of currying before I try to explain it further.

Conclusion

There was a lot of stuff being touched on in this chapter. Core Image, infix operators, and currying. These are complicated frameworks and concepts, so again, don’t get frustrated if you got through this chapter not fully understanding how everything works.

Up next, we have our old functional friends Map, Filter, and Reduce. See you next time!

Functional Programming in Swift: Chapter 2- Thinking Functionally

*Note: I strongly recommend following along in the book with this blog post. I am not going to be recreating the diagrams or the code here, so if you don’t have the book open when you are reading this post, you will be very confused and I would not like that.*

This first full chapter of Functional Programming in Swift introduces one of the most important new concepts in Swift: Higher Order Functions. I will get into higher order functions in a moment, but first I would like to give a little bit of context as to what the example of the chapter is about.

Battleship

The example used for this chapter is called Battleship. I, like many other people, associate Battleship with the board game. Since many programming textbooks use common games with known rules to teach programming concepts, it was understandable that many people thought that this example would be about the board game Battleship. This is not the case.

Back in 1994, the Office of Naval Research was exploring rewriting some of its defense software. Like any good agency, they didn’t want to just pick a programming language out of a hat. They wanted to benchmark which language would be the most efficient language to use for this project. They were concerned with a few factors:

– Development Time
– Lines of Code/How Concise is the Code
– Human Readability
– Maintainability

For a very long time, functional programming languages were considered to be impractical for real world applications. They were an interestring curiosity and another approach to programming, but the enforced static nature of functional languages and the lack of mutable variables seemed to doom functional languages to never be implemented in actual projects.

This study proved that a purely functional language could not only be used effectively in a real application, but also proved that this approach could be even better than an imperative approach.

If you look over a lot of the examples in this chapter, you will notice a lot things that are not present in our traditional games of Battleship:

– Checking the range of your weapons
– Avoiding engaging enemies too close to your ships
– Taking the location of friendly entities into your equations

These are not things we think about when playing the board game Battleship, but they are incredibly vital things to consider if you are a naval ship engaged in battle with actual enemy combatants. These are not small considerations. You don’t want to accidentally frag your fighter jets when you are aiming for an enemy ship. Any targeting program that you design must account for all of these considerations.

This beginning chapter takes this example and shows how Hudak and Jones were able to work around these constraints in a functional manner that was more efficient and easier to maintain than the traditional imperative way of approaching these problems.

Imperative Complexity

Our initial calculation is very simple. We are assuming our ship is at a location and we are trying to determine if another point is within range of our ship. Our range is represented by the radius of a circle and we are simply passing the location of our ship (position) and the distance we can shoot (range).

We are then using the Pythagorean Theorem to determine if our target point is within range of our ship. a squared plus b squared equals c squared. In our case, target.x squared plus target.y squared should be less than or equal to our range squared. Our first function is taking the square root of the two target coordinates and returning it only if this qualification is met.

In order to keep things clear, we are using a type alias so that we don’t have to remember that the CGPoint object is our position and the CGFloat is our distance. We will see type alias again, so don’t forget it.

So far, so good.

As the program grows in complexity, it becomes harder to continue to maintain the function. We keep adding additional parameters and constraints. I am going to honestly say at this point I developed code blindness and stopped looking at the code. Suffice it to say, this once simple function grows to a large mess of spaghetti that kind makes me weep for the future of human civilization.

I am not going to untangle the spaghetti code because we aren’t supposed to be doing this anyway and I am not going to encourage you to write unmaintainable code. Bad Swift developer!!

Going to skip ahead to the functional way to deal with these constraints.

The Functional and Rational Approach to This Problem

There is one very important thing to remember about functional programming versus imperative programming:

– Imperative programming is about telling the computer how to do something.
– Functional programming is about telling the computer what to do.

In the above spaghetti code, we were getting over wrapped up in how the conditional logic would deal with all of the various contingencies of our problem. If our point is in range but it is also too close to a friendly, what do we do? It is easy to get overwhelmed by the complexity of implementation.

So let’s take a step back and ask what are we actually trying to do, without thinking about how it will get done.

We want to know if our point is in a region where we can target it.

Remember when I told you to remember type alias? We are bringing it back here. A type alias allows you to assign a label to an existing type so that if you have multiple objects/properties/variables that are all the same type, you can assign a label to the one specific instance of that type.

We know that strings and numbers and classes are all types, but there is another thing in Swift that now qualifies as a type: a function.

Functions in functional programming are values, no different than strings or structs. They can be passed around and referenced exactly the same way you would work with any other kind of value. The best analogy I can think of for this is a string. In C we didn’t have real strings. Stings were an array of chars that were eventually, in later languages, encapsulated into their own type. As you work more with functions as their own discreet values, it should get less weird to think of them in this way.

We can create a type alias for a specific function type. In the example in the book, we are creating a type alias for a function that takes a Position as a parameter and returns a Bool.

So instead of our initial function that uses the Pythagorean theorem and returns the result of that calculation, we are instead returning a closure that performs the calculation. Closures are simply unnamed functions. Basically we are taking the logic we had before and putting a nice, shiny function wrapper around it. We are wrapping a riddle inside of an enigma.

Why would we want to do this?

Let me give you a real world example of this in practice:

I work at a company called SonoPlot. My boss, Brad Larson, wrote a blog post about our project to rewrite our robotics control software in Swift. Since we are dealing with interacting with hardware, there are a lot of things that can go sideways that you don’t have to deal with when you are working with just software. Sometimes something goes screwy when we are communicating with the hardware and if we just send the command again it will go through just fine. Other times, the hardware is disconnected.

We don’t always know which one of these situations we will be in. We don’t want to keep sending commands to our robotics if they are not connected or on. Alternatively, we don’t want to tell the user that the robotics are not connected when they actually are.

To get around this situation, we created a special function called “runCommandAndAttemptSoftRecovery()” that takes a function as a parameter. We wrap many of our hardware functions in this function. “runCommandAndAttemptSoftRecovery()” will try to run the function we are passing in and if it doesn’t pass, it will attempt run the function again. If the function fails a second time, we handle the error.

Sometimes you will have some functionality that is important to apply to many parts of your project, such as our hardware commands. In times like those, being able to pass a function into the function makes it possible to reuse a piece of code in ways that weren’t possible with Objective-C or an imperative language.

In the example in the chapter, we are trying to figure out a way around the creepy spaghetti code and conditional logic. Rather than creating one Frankenstein’s Monster of a function that has to account for all of these things, we are creating a lot of small functions that account for discreet parts of this problem.

We check if the point is within range of the circe. We check the offset. We write a function that combines known areas that are in range so that they are in one data set instead of two. Each of these functions returns a function of the same kind, so they can work together to narrow down more discreetly if a point is within range of the battleship without hitting a friendly craft.

This is a rather difficult example to explain and I will honestly say that at this point I can only explain it on a high level. I strongly recommend looking at the final code and referring back to each individual function to see how they work together. There are truly reusable functions in the final function that behave differently based on their inputs and parameters. Sometimes looking at a final piece of code and following the logic through its various rabbit holes is the best way to understand how something works. That’s why we dissected frogs in high school biology class, even though I swear some of my teachers were sadists….

Takeaways

This is an introductory chapter. It isn’t expected for you to genuinely grok all nuances of functional programming from this.

Here are the points I would take away from this chapter:

  • Start thinking about what you want your code to do rather than how you are going to implement it.
  • Start trying to mentally break things down into smaller pieces. Instead of having some big, scary function full of state and conditional logic, think about what you are trying to do in smaller steps.
  • Get used to the idea that functions can be passed around like variables. Think of functions as things that take one thing and turn it into something else. If you have a piece of wood, that can be turned into many different things. It can be a table, a desk, or a bookshelf. If you think of a function that takes a piece of wood and returns a piece of furniture and think about how each piece of furniture can be different, this might give you a better idea about how to conceptualize passing functions in Swift.
  • Don’t get discouraged!! This is a different way of thinking. It isn’t going to be intuitive. I have been working on this for nine months and I have barely gotten to the point where this chapter makes sense. That is one reason I am doing these posts. This is just to get your feet wet with some functional concepts. You are not expected to fully understand everything at this point in time. If you feel dumb right now, join the club. You’re not the only one. Just keep working at it and eventually something will click.

I wanted to recommend some resources I am using to try and work through this book to get these concepts to make more sense:

I will try to add to my list of resources as I encounter new ones. If people have sources they particularly like and want to make me aware of them, please ping me at @redqueencoder

Again, if a lot of this is still super confusing, that’s fine. You’re in the right place. We’re all trying to figure out how to please our new functional overlords. It will take a while and no blog post anyone is going to write is going to make this immediately intuitive. Think back to when you learned programming for the first time. It took a while, didn’t it? Learning how to think takes some time and some work. Don’t get down on yourself. Keep at it.

Up next, we are tackling some Core Image. Stay tuned!!