Programming Paradigms
Transcript
(jazz music) - Hey y'all. Let's do this thing. So, welcome to 4 Programming Paradigms in 45 Minutes. When I proposed this talk I did not think they would accept it. When I got the acceptance I'm like, "What the heck am I gonna do?" There are 190 slides in this talk. It's going to be fast. Get ready to hang on. I'm Aja Hammerly. I'm on GitHub as thagomizer. The code from this talk will be posted later today. I need to do some licensing stuff before I can get it out. I tweet as the_thagomizer.
Assuming that the internets and automation work properly, I have tweeted the slides, and that is gonna give you a link to www.thagomizer.com, which is my website where I blog and where I also have the slides for most of the talks I've given. Oh, and I like dinosaurs. I work on Google Cloud Platform as the developer advocate. If you have any questions about Google Cloud, Kubernetes, AvEngine, BigQuery, all that stuff, you can come ask me. There's also three of my colleagues are here. Two of them are up here right now and one I told to go see a different talk so that he could learn from different people. We're also probably going to do a birds of a feather or a lunchtime thing, so watch my Twitter. We'll announce when we figure out when we're gonna do that. And since I work for a very large company, Lawyer Cat says, "Any code in this talk "is copyright Google and licensed Apache V2." So, formalities over. Onward.
So this talk is based on a class I took my freshman year of college. We called it CS 60, although the actual title was the Introduction to Principles of Computer Science. And unlike a lot of CS majors, this course was very early in the major, and it was a survey of all of computing. We did finance, we did automata, we did grammars, we did provability and complexity theory, we did formal logic. But about, eh, 10-ish, 12-ish weeks of the course was dedicated to learning four different programming languages, each of which represented a different paradigm, and solving the same problem in all of them and solving some problems that were designed for that language. And I learned a lot of stuff from this course. More than any other class I took in my major, this one made me the computer scientist that I am. And the biggest thing I took from this class was abstraction. When I started this class I knew Java, I knew some Visual Basic, and some Basic,
but my concepts of things like arrays, and conditionals was attached to the syntax for those things. I thought about them in terms of their syntax. And by forcing four completely languages-- three completely new languages-- four languages all in a very short period of time, I was able to move those concepts from being attached to the syntax to actual abstractions in my mind. If you're a philosophy person, you know Plato's Allegory of the Cave, you kind of have an idea of what I'm trying to get at here. The other thing I took was that I too could be a polyglot. I was always impressed with people who knew a lot of computer languages, but when you learn three new languages in nine weeks, and you're able to be productive with them, you realize that once you have the concepts and the abstractions down, the syntax really isn't that hard. And when you're a polyglot, you can point out the similarities between languages.
Concepts like conditions, and collections, and arithmetic, and loading and storing things from memory, they show up over and over again in different languages and different ways. And so understanding those at a conceptual level, as opposed to, "I use this syntax for arrays," is really helpful. And the other thing it taught me is there are big differences between programming languages, and different languages are good for different things. And I'm hoping that you guys will take some of that out of that 45 minute crash course, where I try to cover what I learned in 18 weeks in 45 minutes, I hope. But don't worry if you can't keep up. This is supposed to talk about ideas, even though there's a lot of code. When I took the class, our primary example was solving the puzzle Towers of Hanoi, with the little rings and the pegs. You have to move the tower from one peg to the other. Explaining the algorithm to do that and then explaining that in four different languages
is going to take more time than I have, so we're gonna give you something much simpler. I'm gonna talk about change. And by change I mean this kind of change. In each language I'm going to show you how you would calculate the amount of change you would give if you were a cashier working a cash register. Everyone following? Let's dive straight in. We're gonna start with OO. We're at Rubyconf so we're gonna use Ruby. I color coded my slides. Ruby is of course red. And we're gonna start with something easy. The code gets harder as we go along. That's just how it is today. So let's talk a little about OO. Everything in Ruby is an object. Everything. False is an object. False is a singleton instance of an object. Null is an object. Your classes themselves are instances of the Object class. Not all OO languages are this pure, but the general idea in OO is that most things-- I would prefer all things-- are objects. Well what's an object?
An object is a way of encapsulating state and behavior. State is things like fields, attributes, instance variables, what you call them varies a little depending on the language and your particular background. And behavior is what you do with that state, things like methods. Most OO languages, the object is responsible for modifying its own internal state. In Ruby we call this self. So if I was an object, I could say self.pets equals the array Emma, Nick, and Shy, because those are the names of my cats. Objects have to interact with each other, because, you know, an object just sitting there by itself is rather boring, and the way they do that in Ruby is through message passing. If I want to find out the length of an array,
I send the message length to an instance of an array object. That object calculates the length of its internal state and then returns that length to me. So when I'm teaching stuff, I normally try to use my own examples, but since we're going super fast today I'm going to try to use examples that are canonical, or common place in literature, so that hopefully you can kind of attach this to something you may have seen before, hopefully. And one of the most common examples for OO
is the idea of a bank account. So I'm gonna build up a bank account object. Well, objects are instances of classes, so class BankAccount. Bank accounts need to have a balance of some sort, and for a lot of reasons it's a bad idea to allow folks to monkey with my balance, which is my internal state, so I'm gonna store balance as an instance variable, and I'm gonna set it to zero when I initialize the object. Note, I'm going to talk about money a lot today, and I'm always going to represent money
as an integer number of cents. If you are representing money as float in any of your code, come talk to me later and I will teach you about why that is a horrible idea. (laughter) So. I'm gonna take a break for IRB. I can go BankAccount.new and get an account object back. Now I know since I wrote the code, my balance is zero, but I can't actually see it. So let's write an accessor. So I'm gonna have an attr_reader because I don't want anyone outside to be able to set the balance, and that's gonna return balance. Back to IRB, now I can see my balance. It's zero. So a bank account with a balance of zero is pretty much useless, so I'm gonna add ways to withdraw and deposit money.
So, deposit is going to increase the balance. Deposit is a message. It takes an amount and it adds that to the balance. Withdraw is the opposite; It takes an amount and subtracts that from the balance. And you can see from my IRB break here that it works. So I talked about an object having both data and methods before. In this case the data is the balance, and the methods, or the behavior, are deposit, withdraw, and initialize. And all of these methods modify the internal state of the object, and my IRB process is communicating with them by passing a message like deposit with an amount and trusting that the object will do the right thing with that data in that message. So some of the strengths of OO. It's really good at modeling what we do in real life. So like I have a chair here. I can have a chair object. It can have an attribute color. It can have behavior, hold me up, those kinds of things.
We think about the world through concepts and ideas that very closely align with objects. We don't think about the world as the chair's color is fundamentally separate from what it does. Objects are also reusable. A good way to see this is think about the standard library. Arrays are objects, hashes are objects, strings are objects, and we all reuse them in all different ways because the same types of concepts in objects show up again and again and again in the problems we're trying to solve. And this means I don't have to implement array.length over, and over, and over. I think objects are easier to test. I can test the object in isolation, and test that it modifies its own behavior correctly, and then I can test the seams between the objects when I'm testing my system as a whole. So, on to the motivating example. So I'm gonna do the making change algorithm, OO style.
Here's the code. So this is like 28 point font and I don't expect you to be able to read it, so we're gonna build this up piece by piece. So I have a class, I'm gonna make a class called CashRegister, because that's what I use to make change. My CashRegister has a cash drawer. That's the thing that slides out that contains the money. The drawer contains a bunch of different denominations of bills and coins. I have 20s, 10s, 5s, and 1s, and then I have quarters, dimes, nickels, and pennies. If I was doing a more thorough implementation I could have the amount of each that I have in addition to the denomination. Here is the method that makes the change. It's still kind of small, so let's build that up piece by piece too. Here's the method signature. Make_change takes an amount owed. This is the amount that the customer owes the store. And it takes the amount the customer gave the cashier, which you'll see frequently referred to as tendered. Not Tender Love, Erin.
So the first thing I need to do is I need to figure out how much change I have to give the customer. And this is gonna be the difference, and to do that I subtract the owed from the amount tendered. And then I'm gonna represent the bills and coins I need to give the customer in the change array. This is gonna be the thing that tells the cashier five fives, three ones, blah blah blah. The next thing is I need to figure out which part of the drawer I'm working in. When I've seen people make change, a fair number of people will start at one end, either the smallest or the largest, and move down the drawer, and grab the appropriate amount and then move to the next slot, and the next slot, and the next slow. So I'm gonna do that exact process with my array that is my drawer and I'm gonna use i to index where I am in that process. And, you know, it's a loop.
While I still have change to give the customer, while difference is greater than zero, I'm gonna loop through this thing. So, expanding on the loop a little bit. Here's the first part. If the difference, the amount I still need to give the customer is less than the current denomination I'm looking at, the current slot in the drawer I'm looking at, that would be the case where I have to give the customer $4.50 in change, and I'm currently looking at the 20s. I can't give them a 20, so I need to increase my index and set my denomination to the next smallest thing. Now I'm making an assumption throughout the entire talk today that the change drawer is always sorted largest to smallest. If it isn't, none of these algorithms work. And once I've done that I can go back to the start of the loop and try again. So the next part is-- Now this is the case where I'm giving 4.50 in change but the current thing I'm looking at is $1.
I'm gonna say well, that's not bigger so I can use that one, so I'm gonna add it to the list of change I'm giving, and then I'm gonna subtract that amount from the amount still owed to the client, or the customer. And then I go back to the top of the loop and I keep going through this, and eventually I'm going to have the change I need. And this ends up with this method. So those of you who really like your OO are like this is not OO, and you are totally right. This is a really, really bad problem for demonstrating OO. And that brings up the point that different programming languages are good for different things. But this is a fine problem for demonstrating the other three paradigms I'm gonna talk about today, so that's why I used it. This actually looks much better as a functional program. Onto our second paradigm. I'm gonna use Racket, which is a general purpose programming language in the Lisp family.
Lisp, in turn, if you have never heard of it is the second oldest multipurpose high-level programming language. Lisp stands for List Processor. The only language that is older than Lisp is Fortran. And Racket and Lisp are well suited to demonstrate functional languages, although both of them are not limited to that paradigm. You can also use Ruby for functional languages, but I'm four languages, 45 minutes, that was the promise of the talk. So, an overview. Functional languages are built of functions! Who would have thought. (laughter) Functions take in data and output data. I'm gonna focus today entirely on pure functional programming which means that my functions don't ever store state and they don't ever mutate the incoming data. So, if you give me an array I will give you back a new array, I will not modify the one you gave me. So no bang methods if you're still in a Ruby mindset. A nice thing about pure functional style
is the output only depends on the input, it doesn't depend on what came before. So I can do a bunch of stuff and then give the same input and it will always be the same thing; History doesn't matter at all. And the really fundamental things of functional languages is that data and procedures, state and behavior, are separate, unlike OO where they're encapsulated together. I'm hand waving a bit here, it's not actually entirely true, but for the purposes of this talk it is true. So, for all the languages that aren't Ruby I get to teach you syntax. The biggest thing you need to know about Lisp family languages and Racket in particular is that we're used to things like Ruby that use infix notation, but Lisp languages and Racket use prefix notation. So to add three and five I use + 3 5. And you're like, "Well that's weird," but it's actually super useful because I can do one times two times three using only one times symbol, which I couldn't do in Ruby.
* 1 2 3, that multiplies all of those together. I'm not limited to just two arguments, which you are with infix notation. And you're like, "Well that's completely impractical. "How can you do multiple levels of it?" Well, the answer is on the last line there. I'm multiplying three and five and subtracting six from 10 and then I'm adding the two results together. And you just use multiple levels of parentheses. And I really like this because the order of operations is very, very explicit. So, math is not particularly interesting on its own. I need to be able to write my own functions. You declare a function by putting the word define, and then in parentheses the name of the function and its argument list. The square function takes one argument and I'm calling it n. And then after that I have the body of the function. In this case I'm multiplying n times itself. To call that function I go parentheses, function name, argument. Square of five is 25.
I of course need some way of doing conditionals, and I'm gonna use the conditional from Racket called cond, which is short for conditional, and it acts like Ruby's case statement. So I have a cond, and then the first thing is, on the first line I have a test, and then there's some stuff to do if that test is true, and then I have a different test, and there's different stuff, and then there's an else, and there's more stuff. Very similar to the case statement. And here's a concrete example. This is calculating absolute value of x. If x greater than zero, well the absolute value of that is gonna be itself, so I return itself. If x is equal to zero, well the absolute value of zero is zero so I return zero. In all other cases I now know that x is a negative number so I'm going to return the negation of x to give me the positive x.
The only thing you need to know is lists. As I said, Lisp, List Processor, lists. This is a list. I represent it as a set of items separated by spaces inside parentheses with a little tick in front. The tick is there because otherwise I wouldn't know if this is applying the function 1 to 2 or 3 or if this is a list one two three. Because remember, prefix notation. This is not a function call. When you have lists, I can access the first thing in the list by calling the car. These names will come back later, I promise. That gives me the first thing in the list. Or I can get cdr, which gives me the rest of the list. You might also hear me say today "head" and "tail". I mean first and rest in those cases, or car and cdr. And I can make lists by using cons. In this case I'm am consing the item one onto the list two three which gives me the list one two three. Some examples. Here's factorial. We use recursion a lot in functional languages. So I have a cond.
If the item I'm trying to get the factorial of is one or less, I return one, because the factorial of one and the factorial of zero are both one. Otherwise I multiply n by the factorial of n minus one, which recursively gives me the factorial. Fibonacci. This will give me the nth Fibonacci number. So if n is less than or equal to zero I return zero. If n is equal to one I return one. Otherwise I sum the nth minus oneth Fibonacci number and the nths minus twoth Fibonacci number.
That's the definition of Fibonacci. Some of the strengths of functional programming. If I'm doing pure functional programming and I'm not modifying state at all, I don't have to worry about all of the stuff you have to worry about with concurrency and threading because we're not sharing memory, we're not having to lock tables. None of that stuff is even important because nobody is modifying state; Everything is just a read operation. That's really handy a lot of the time. I think that functional programs are easier to test than some of the other ones because state doesn't matter. Data in, data out, especially pure functional programs, which means that the setup for automated tests is just, "This is the data that I'm going to run it on." I don't have to set the state of an underlying object first. And because there's no state, you can also reuse this. I can take code that works in one program and throw it in another program and I don't have to worry
about there being context surrounding it that's required. And I really like that they're short. Functional programs tend to be really short, especially in Lisps. A lot of people hate this, but it makes me happy. So, on to our motivating example. Here's the code that makes change in Racket. And I'm gonna actually slow down a little bit here because I wanna make sure that you sort of understand this. So here's the function signature. It is a function of two arguments. X is the amount of money I need to make change for, and denoms, denominations, is the denominations of bills and coins that are available in my cash drawer.
So now I have a conditional. The first case I want to check is if the amount I'm trying to make is zero I don't owe any change, so I can return a list that is empty because the list I'm returning is what bills I need to pull out of the cash drawer, and what coins. So, how do you make change for zero? You give someone nothing. Empty list. The next thing I'm gonna check is do I have any money in my cash drawer. If there are no denominations, there's no bills or coins in my cash drawer, I can't make change, so I'm gonna return false.
So these last two cases are the tricky ones. So this is the case where the amount I'm trying to make is less than that first denomination. Car denoms is giving the first element of the denoms list, which is the highest bill in the cash drawer that I'm currently looking at right now. If that amount is less-- sorry, is greater than the amount of money I'm trying to make, I need to use the rest of my cash drawer. So if I'm trying to make change for 4.50 with a $5 bill I can't do that, I need to use the rest of my denominations to make change for x. So I do a recursive call. Finally, and this is the case where I actually use that first bill. So remember, I'm trying to return a list, and I make lists with cons, so I'm consing the first element of my denominations thing, which might be my $5 bill, onto the recursive call
to make change for the rest of the amount, and I calculate the rest of that amount with that subtraction there. That's like that difference equals line in the Ruby. And then the same set of denominations I'm working with, because I might need two or three pennies, I might need to use the same denomination more than once. This is the case where I don't use the current thing I'm looking at. This is the case where I do. There's really only two cases beyond the base. So, I really, really like this. It's much shorter than the Ruby. I think it's very, very logical and if you've got some background in number theory or mathematical theory and you're used to proofs by induction, I think the recursion looks very familiar, and very comforting. But this is not actually the shortest solution to this problem that we will see today. That is given to my friend Prolog.
We're going to do logic and constraint programming, and this is going to most likely be by far the most brain-breaking part of the talk. So I will try to take it slow and you can come up and talk to me about Prolog later, I'm happy to demonstrate all this code. So, I'm gonna give an overview of Prolog. Prolog is based on formal logic. Things like Socrates is a man, all men are mortal, therefore Socrates is mortal. So ands, ors, implications, nots, that kind of stuff. Very, very basic formal logic that's used in philosophy and mathematics and also is the basis of a lot of computer science. Prolog programs aren't made up of instructions, they're made up of facts and clauses. Yes, that's weird. And the weirdest thing about Prolog is that instead of describing the how-- We're used to in programming telling the computer how to solve the problem. Prolog works different. You describe the what of the situation. One of the common examples is a logic program.
So I would say, okay the logic program says that the guy in the yellow house does not own the fish, and I would encode that. Or I would say that the guy who really likes to drink rum lives next to the man who owns the cat. And I can code all those facts in the system and then what Prolog does is it uses everything it knows and it tries to come up with a world where all of those are true. And it fills in any blanks that are remaining once it comes up with the world where all of those facts and clauses are true. So syntax to do this is a little weird. The biggest thing is that we have variables and constants. Variables start with a capital letter. Constants don't, they start with a lowercase letter. And then we have facts, and facts end with a period. So I can say that Washington is a state, or that Washington borders Oregon, and Washington borders Idaho, and Oregon borders California.
And using this I can define a rule, and rules specify relationships between facts. So here I'm defining the rule adjacent. And that colon minus sign is actually a logical implication. If you know what that means that might help you understand this. But all this is saying is that X and Y-- now those are variables because capital letters-- are adjacent if there is a fact where border X and Y is true. And what Prolog is gonna do with those variables is it's gonna try to pattern match. It's gonna go through all of the facts it has and figure out if there's some constant it can put in for X and another constant it can put in for Y, or the same constant, where there's a fact that matches.
And this is called pattern matching, and pattern matching languages are awesome. And so here's my adjacent rule again. Now here are the facts I have, some of them, and here's the adjacent rule, and I can go into an interactive Prolog terminal and say, "Hey Prolog, is Washington adjacent to Oregon?" And it will say yes. And then I can go, "Hey Prolog, is Oregon adjacent to Washington?" And Prolog is gonna say no, because Prolog is incredibly literal. And since I only have a fact that says that Washington and Oregon share a border, not that Oregon and Washington share a border, Prolog doesn't know that the reflexive case is true for this particular rule. So I have to teach Prolog that by saying that adjacent X Y implies that there's a border between X Y, but adjacent X Y can also imply that there's a border between Y and X. I got a little tricky there. And then if I go in and I say, "Hey Prolog, "is Oregon adjacent to Washington," Prolog will correctly say yes.
And I have a couple minutes so I'm gonna go over my favorite Prolog joke. How many Prolog programmers does it take to change a light bulb? Anyone know? No. The answer to that is no. (laughter) I'm gonna give you some basic examples, and the canonical example in Prolog is ancestors, building your family tree. So I'm using the Simpsons. And one of my first rules, first facts is that father(homer, bart). So that's saying that Homer is Bart's father. You have to change the word order around a little bit to make it work in English. Not true in other languages that have different word order than English. You can also say that Homer is Lisa's father. You can say that Marge is Bart's mother,
and Marge is Lisa's mother. So then I can go into my interactive Prolog terminal, I can start asking questions. I can say, "Hey Prolog, who is Bart's mother?" And that's the first line there. What I'm actually saying is, "Hey Prolog, what do I need to shove in for X? "What value of X makes this statement true?" And Prolog is like, "Marge is Bart's mother," which is correct. And then I can say the opposite, "Hey Prolog, who is Marge the mother of," by putting the variable in a different location.
And Prolog says Bart, and then I can use the semicolon to say, "You got anything else," and Prolog will say, "Lisa." And this is the real strength of Prolog, is that I can run programs backwards and forwards and I can put variables wherever I want. And it is crazy the first time you do this, but it is also super duper powerful. And I've showed you simple examples thus far, but you can build rules that are much more complicated. So let's build the rule sibling. X and Y are siblings if there is some Z such that Z is the mother of X, Z is the mother of Y, and X and Y are not the same person, because you can't be your own sibling. And that \== is "not equal" in Prolog. But there's another way that you can be siblings. X and Y are siblings if there is some Z such that Z is the father of X, Z is the father of Y, and again, X and Y are not the same person. And Prolog is gonna try to figure out whatever values
it has to put into each of those capital letter variables to make this true. So I can go into the interactive Prolog terminal and say, "Hey Prolog, who are siblings?" And it says, "Oh, Bart and Lisa are siblings." Awesome. So, I'm gonna go into the last bit, and this is one of the most complicated bits of Prolog that we're gonna talk about today. Prolog has lists, like Racket, like Ruby. I have an empty list, I have the list one two three, I have a list apples and bananas. So I can have lists that are heterogeneous, I can have lists that have numbers or constants in them, and I can also have nested lists, which is what I'm showing on that last line. But in order to pattern match on lists I have to have some crazy notation. This is called bar notation. I'm gonna say this aloud as "F bar R." You can think of the F as first and the R as rest. And this is just like the car and the cdr we saw in Racket. F is the car, it is the first element of the list.
The bar separates the first element from the rest of the list which is the cdr. And if that didn't make any sense, if I have the list one two three and I pattern match that against F bar R, F is gonna match the one, and R is gonna match the list two three. So car and cdr, same thing. Crazy notation. The last little bit is this is an underscore. So I might break some of your brains, I hope not, but did y'all know that you can use the underscore to say, "I don't care about this variable, it's unused," in Ruby? Good, people are nodding. This is fantastic. I've broken people's brain with that one before. Racket has the same thing. Underscore in Racket is called "meh". I like that. (laughter) I learned that from Ryan Davis last night. And then in Prolog texts we refer to this underscore as "don't care," which is, this variable isn't actually used for any of the logic, so put whatever you want there, I don't care.
So we're gonna do a quick list function. List rule, not a function. Not in a functional language. So this is member. It's like include? in Ruby. So X is a member of the list. First argument is the thing I'm looking for, the second argument is the list. X is a member of this list if X is the first thing in that list. Makes sense, right? That's one case. Oh, I forgot to change the bold. The second line, X is a member of this list if I don't care about the first thing, it doesn't match,
but X is a member of the rest of the list. So X is a member of this list implies that X must be a member of the rest of the list. So recursion. It's handy that way. So strengths. One of the awesome things about Prolog is that thing I mentioned about running programs backwards and forwards, this is true of logic programming in general. There's a great talk about Mini Cameron where they actually run their logic system backwards to generate the code for factorial.
Because why not? You can run it backwards and forwards as long as you setup the constraints correctly. One of the early use cases of Prolog that I read about was actually scheduling time to use limited resources in a research lab. I believe the resource was a dolphin and they needed to figure out how to work everyone's schedules around. Like, this experiment is gonna take 45 minutes and we need to repeat it every three days for a month, and I have class at this time and all that. These Prologs, you put all those constraints in and solve the problem so that they had a reasonable shift schedule. So, time to make some change.
So, we're in Prolog. The weirdest thing and the thing that always gets me when I have to context switch into this language is I don't have return. There is no concept of a return. Everything is encoded in the method signature, and you have to have that so you can run it backwards. So, we're gonna have a change rule. It has three arguments. The first is the amount. The second is a list of coins or bills that we have. And the third is how you make change for that amount using that list of coins. The first one is an integer, the second two are lists. So this is going to be true only if
change, that last argument, is how you make change for the first amount using the coins in the middle. I think it might have just snapped for a couple people, this is weird. So, here's the code for the change function. It's actually shorter than the Racket. (laughter) We'll go through it. I promise, I promise. So, first case, the easy case. How do I make change for the amount zero? Well change for the amount zero is the empty list. And I don't care what's in my cash drawer, which is why I'm using the underscore, because I don't need to know. We don't need to use anything from the cash drawer if I'm making change for zero. That's the easy one. Here's the second one. Focus just on the first line right now. There is where we use pattern matching. So I've got an amount A. And this is saying that I make change for the amount A by using the first thing from my cash drawer, and that is the first thing in the way I make change. So this is the case where I use
that first bill or coin in the cash drawer. And I can only do that if the amount is greater than the denomination of that first thing. And if those two things are true I need to calculate B such that that is the difference between the amount, that is what's left over after I use that bill, and the other thing that has to be true in that case is that I can make change for B using the same stuff in my cash drawer, and the way I do that is X, which matches that X on the very top there. So, A is greater than F. I can use this because the bill is smaller than the amount I'm making. B is equal to that difference, the remaining amount of change. And the way I make change for B is X,
which matches on that top part. And remember, Prolog is gonna make all of the instances of each variable the same thing. So that's the second clause. Third clause. This is the case where we don't use the first coin or bill. So I used a don't care again. I only want to apply this one if I'm actually making more than zero in change, because if I'm making just zero I can use the first one above, the very first one. In this case I'm going to say hey, the way you make change for A is you use the rest of the stuff in your cash drawer, and the way you do that is X. So this is the other recursive case. And I promise it works. And you're probably going, "Ow, my brain," right now. I love Prolog, and this was the hardest of the examples for this talk to write. I actually had to break into the debugger to do it, and I didn't have to do that for even what's coming next, which is procedural. And we're gonna do that with assembly. (laughter) So the fact that I was able
to write the assembly without the debugger and I needed the debugger for the Prolog; The Prolog is hard. Assembly is old-school programming. We have a limited vocabulary, a limited standard library, a limited number of functions we can call. And by limited I mean very limited. For the assembly I'm using, I think there are less than 30. I think there's like 22. And there are tons of assemblies that exist. I am using the assembly from a book called-- It's commonly referred to as NAND to Tetris. I'll have a bibliography entry for it in the end so you can grab it and check it out yourself. The reason I'm using this is that it is less ugly than most assemblies, it looks more like the programming you're used to, and it's very, very simple. So, here's the syntax. So the big thing about the assembly is that I have two registers, A and D, and those are the only two things that I can do operations on. D is D because it is the data register. A is A because it could be a data register,
or it could be the address register. And when it's the address register, I use whatever value is in A and I go pull that cell out of memory. So in the cases where I'm using A to access memory I'm gonna actually just call it M. So I'm gonna use A, D, and M, but I only have two. It's just when I'm using M, I'm using what A is pointing to, and when I'm using A I'm using the actual value of A. And circling back to Racket. We had car and cdr. Car stands for the contents of the A register. Cdr stands for the contents of the D register. That's where the names came from. So we've got some computations. I can do A plus D. I can do D minus A. I can do A minus D. I can do A plus one or D plus one. I can do A minus one or D minus one. I have a bitwise-NOT, a bitwise-AND, and bitwise-OR. And I can negate A or D. And any place I use A I can also use M. So like M plus one, or D plus M. And that's it. That is the contents of the list of things I can do.
And important to note, I don't have multiplication. Don't have division. Don't have anything that remotely looks like a list. Very, very limited. But I can actually assign the things I calculate to values. So I can assign to any of the registers or to memory. So I can say D equals M plus one, or D equals D minus one. And I can also do multiple assignment, so I can say M and D both get the value of A plus one, which is crazy because then I'm incrementing the memory register...
Yeah, that's a bad idea. I need to be able to get constants into my program, and the way I do that is with @ syntax, and constants can only go into the A register, that's why it's @. So if I want a (mumbling) hundred I do @100. If I want I can have a label. And I use this label somewhere in the program to access the line of my program that this label is on. And again, this is an @, goes into the A register, and I use this for jumps. Jumps are of this format.
There's a value, a semicolon, and then the type of jump. And so I'm like, the value in this example is D. JGT is jump greater than and I will jump to whatever line of the program is in the A register if D is greater than zero. I don't get to have any other greater thans, it's always in reference to zero. So I have JEQ, jump if equal. And so this will always jump, because I'm jumping if zero is equal to zero. Jump greater than, jump less than, jump greater than or equal to, jump less than or equal to. I also have a non-conditional jump which is JMP. So those are the jumps I have. Those are the only form of branching logic I have in this entire language. So here's how we add. This loads in two into the A register. I then move the contents of the A register to the D register. This loads a three into the A register
and I add what's in my D register to my A register and assign it to myself. And then I take whatever is there and I assign it to the contents of memory cell zero. It's memory cell zero because I put a zero in the A register and then I'm using an M, which means it refers to memory, not to the value of A. See? It's easy. (laughter) Here's how I sum the digits from one to five. I'm actually doing it backwards. So first thing I do is I'm gonna store them, I'm gonna store my result in memory cell zero. So I want to zero out memory cell zero. And then I'm gonna store five in memory cell one. So I load it into A, assign it to D, and then load address one in A and then assign whatever is in D, which is five, to memory cell that's referenced by the address in A, which is one, so I put it into memory cell one. Here's my loop. The parentheses notation is a label. First thing I do is I pull whatever is in memory cell one,
which is five in this case, and I put that in D. And then I'm going to take whatever I have in D and add it to the contents of memory cell zero, which is my accumulator. So now memory cell zero is five and memory cell one is five. And then I'm gonna take the contents of memory cell one and I'm gonna subtract one from that. So now I've decremented to four, and I'm gonna store that both back in my memory cell one and in D. And then I'm gonna do my logic. And here's my loop. So I'm gonna load END into my A register. This is where I want to go, and it's the end of my program if my program is over, and I know my program is over when my counter has gone from five, to four, to three, to two, to one, to zero. And so if D is less than or equal to zero, I'm gonna jump to the end. Otherwise I fall through to my LOOP label, and I'm gonna go back to the top of my loop in all other cases because I have an unconditional jump there. Awesome.
So strengths. There are no strengths. (laughter) I don't have use for assembly on a daily basis. I'm really hoping that none of you do too. But procedural style in and of itself can be useful, and you can write procedural style in any language. Most of us, our very first program was procedural. Hello World is totally procedural. All of the scripting stuff we write is generally procedural. Do this thing, then do this thing, then do this last thing. And writing procedural code is generally pretty easy. For most of us our brains instinctively think this way. So here's making change in assembly. (laughter) I don't have lists, so I'm gonna use memory zero for the amount to make, memories one through four for my coin denominations, 25, 10, five, and one, and I'm gonna memories five through eight for the number of each coin to use. Because I have memory, we'll turn it into a list. The assembly I'm using doesn't understand this M syntax, it uses R instead, so you'll see this in the code. So this loads--

Ask anything
We've read this whole study set, so questions about it get the best answers.