Recherche
Nombre de résultats à afficher par page
Résultats de recherche
-
- Créateur:
- Peirce College and Littlefield, Cathy
- La description:
- syllabus for 7-week (accelerated semester) course on organizations and people
- Type:
- Text
- Type de ressource d'apprentissage:
- Reading
- iveau d'éducation:
- College / Upper division
- Public:
- Instructor
- La discipline:
- Business - Management
-
- Créateur:
- Peirce College and Littlefield, Cathy
- Type:
- Text
- Type de ressource d'apprentissage:
- Syllabus
- iveau d'éducation:
- College / Upper division
- Public:
- Instructor
- La discipline:
- Business - Management
-
- Créateur:
- Littlefield, Cathy and Peirce College
- La description:
- reading list for 7-week (accelerated semester) course on the introduction to supervision and management
- Type:
- Text
- Type de ressource d'apprentissage:
- Reading
- iveau d'éducation:
- College / Upper division
- Public:
- Instructor
- La discipline:
- Business - Management
-
- Créateur:
- Littlefield, Cathy and Peirce College
- La description:
- MKT 101 reading list by week for a 7-week (accelerated semester) course
- Type:
- Text
- Type de ressource d'apprentissage:
- Reading
- iveau d'éducation:
- College / Upper division
- Public:
- Instructor
- La discipline:
- Business - Marketing
-
- Créateur:
- Feliciano, Shannon
- Type:
- Text
- Type de ressource d'apprentissage:
- Syllabus
- iveau d'éducation:
- College / Upper division
- Public:
- Instructor
- La discipline:
- Social and Behavioral Sciences - Sociology
-
- Créateur:
- Littlefield, Cathy and Peirce College
- La description:
- Syllabus for a 7-week (accelerated semester) course on marketing fundamentals.
- Type:
- Text
- Type de ressource d'apprentissage:
- Syllabus
- iveau d'éducation:
- College / Upper division
- Public:
- Instructor
- La discipline:
- Business - Marketing
-
- Créateur:
- Gretchen Gueguen
- La description:
- Video of lecture on metadata from LS 575 "Digital Libraries" course in the graduate program in Library and Information Science at Clarion University.
- Type:
- MovingImage
- Type de ressource d'apprentissage:
- Lecture
- iveau d'éducation:
- Graduate / Professional
- Public:
- Instructor
-
- Correspondances de mots clés:
- ... Were going to expand our understanding of metadata this week to talk about how it can be shared and applied in even more interesting ways. 1 Lets just quickly review what we talked about last week: Metadata is information about an object Metadata is organized into schemas, which are sets of elements or properties that are used to describe characteristics of an object. Similar elements can be differentiated by attributes, hierarchy, or membership of a class Metadata is what is searched in a digital library There are several types of metadata including descriptive, structural, and administrative types: preservation, rights, technical Some major metadata schema used by libraries include Dublin Core, and MODS, 2 Before we move on I want to take a little side-track and talk a little bit about XML, which stands for eXtensible Markup Language. XML is basically a protocol, or set of rules, about how you can format text in a way that certain software can understand. The reason we are learning about it is that a lot of metadata in the library community is shared in an XML format. The rules of XML have you put property names inside angle brackets. The property name is in an angle bracket right before the text of the value. When the text of the value is finished, the property name is repeated again, but this time with a slash. So the properties wrap around the text of the value. In XML, properties can be nested and hierarchical, so you can have that idea of hierarchy or classes, like weve talked about. But every XML document must have an initial, or parent, root element, that will open and close the file. XML is just one of many different data encoding standards. There are other sets of rules that might dictate how to format metadata slightly differently for different types of programs to read (kind of like how there are different citation standards for different disciplines that all dictate how to format the same type of information in a citation). XML is a very common format used for metadata in libraries. 3 So heres a look at some XML. Book metadata is the root property. It is enclosed in angle brackets. The property inside its angle bracket is often referred to in XML as a tag. We can see how opening and closing tags contain all of the text values within them. An attribute is expressed in XML by being within the opening tag and using an equal sign (type=created) We can see that XML properties are repeatable. And also hierarchical, meaning tags can wrap around not only values, but also other tags like the way a parenthetical statement is inside a sentence, This is a faked metadata schemaif you wanted to make an XML record using the Dublin Core schema, you could go to that reference and find out what the properties are for that standard and then write it up as XML. Same for MODS, or PREMIS, or VRA or any metadata schema. If you remember, back in our week on text digitization we also saw some XML. That time it was using a schema called TEI that is used to mark up text values. If you are familiar with HTML that is also a metadata schema that is often employed using XML. 4 One other basic concept I want to cover is the Application Profile. In a typical scenario, if you have a digital library that has a wide variety of material, you might find that no one schema is going to do the job for you really well. An application profile then is a local schema that incorporates elements from different standard schemas into one profile. Its like picking menu items from an ala carte menu, sort of. This website, created by a subgroup of the Digital Library Federation, is a clearinghouse for metadata documentation including application profiles. Its a new thing and small now, but hopefully will grow over time. Lets look at the application profile from Rice University in the clearinghouse. All it really is, is a list of elements taken from several schema that this university wants to use to describe Electronic Thesis and Dissertation. The rest of the docs are just some info on the definitions of these elements. Rice then takes these directions and creates metadata records for its Electronic Theses and dissertations that follow these rules. Its as simple as that really. 5 Lets look at another example, the application profile that DPLA uses. This is a document that lays out the application profile used by DPLA to ensure that all of the records they share are the same schema. On page 5 you can see a declaration of the different schema used in the profile. Looking at the table of properties used, you can see that a lot of them are from the DC and DCTERMS namespace. But there are a few that DPLA has created for themselves because they couldnt find a schema with these specific things. By using an application profile, they only had to create two new properties, rather than declare an entirely new schema just for their purposes. 6 The way you distinguish where the different elements come from in an application profile is through the use of namespaces. This takes the XML we just learned about and adds a new feature to the tag or the property, a namespace declaration: the blue parts there are the namespace: just an abbreviation identifying the schema the property comes from. By adding that, we are saying that we are using title and format in the way they were described according to simple Dublin Core, we are using namepart as per MODS, we are using dateCreated as per dcterms (thats a schema that uses the qualified version of Dublin Core), and we are using measurement from VRA. By mixing and matching elements from different schemas we can create one that is customized for our specific needs, while still working with standardized schemas. Application profiles are now very common. 7 Now that we understand application profiles, which was really the last of the very basic concepts, lets move on to talking about how metadata interacts with the rest of the networked world. One of the first things the information world started to get excited about when they starting putting data online was the opportunity to share it. This could take the form of their metadata records simply being indexed by a search engine like Google, or it could involve in some library-based aggregation project: For example, if two libraries in the same town had their data online in a metadata format, theoretically you could build a tool that would search both of those data sets together. There are two primary ways to share metadata for combined searching. One is federated searching, which creates a tool that is smart enough to go out and search a bunch of sources simultaneously. In this type of sharing the issues of consistency and structure arent as important because you can customize the search to the source, and the data is always up to date. However, the searching can be slow. It is at the mercy of the speed of the local institution. And there can be problems with determining relevance for ranking results of queries between the sources, because they might have different metadata schema that arent compare-able. Another method is aggregation. We are going to talk a lot more about aggregation this week. This is when a service goes out and collects records from a bunch of 8 different sources, puts them all into one index that is then searched. This means that the single index can be searched really quickly. However, that index will have to be periodically updated to reflect additions and changes at the various sources. 8 The Open Archives Initiative Protocol for Metadata Harvesting (OAI PMH (usually just referred to as OAI) ) is a technology that makes metadata aggregation possible. OAI is based on two different roles. The first is the data provider, this is the organization that has records they would like to share. The second is the harvester, this is the organization that is gathering the records OAI specifies a protocol with directions for how to either publish or harvest metadata using HTTP another internet protocol (or set of directions for how to do something). The idea of a protocol is that there are tons of different ways to do this, but if we all do it the same way -- in other words, follow the same protocol that OAI has set up -- then its easier to cooperate without a lot of figuring out the wheel each time. Besides the protocol there really arent a lot of requirements, so you can share metadata in any format as long as it is expressed in XML 9 Lets look at this in action This is a digital collection at the Montana State University. You can go to their website and see these items in their collection. 10 Or you can go to their OAI feed urlthis one was set up for them through the Big Sky consortium in Montana. They set up an OAI server at this address that will output these records according to the OAI protocol - To start the query I type ?verb= - Then I include whatever OAI commands I want to use Lets try this in real time - Now this is how I as a single person who wants to look at the records in these feeds would do this. In a situation with an aggregation service, they would build some sort of software that would use the OAI protocol for harvesting to build a tool that would do this for the thousands of records in this feed and others and then save them in a new database. They then could make them all available through a new user-based website. 11 Like this one at DPLA. They have an OAI harvester that will run and maybe capture 300,000 records in a couple of hours. They put those records into their own repository and then display them on their website. They may still end up with records in lots of different schemas though because some partners might use MODS, some use Dublin Core, some use MARC so the next thing to do to get the records to be searchable together would be to convert them all to the same schema. 12 The first step in being able to transform, or map, that metadata from one schema to another is to create a crosswalk. The crosswalk is just a plan for what properties in the source schema we will convert to which properties in the schema we want to end up with. Often there are not 1-1 matches between schemas, so things can get complicated. But its basically like translating the values from one schema to another. That crosswalk can then get transferred to some code in a scripting language like Python, or PERL, or Ruby, to create brand new records in the schema we want to end up with, based on the ones that we started with. The way I think of them, mapping is the term usually used for actually doing that transformation and the crosswalk is the directions, but the two terms are often used interchangeably in the profession. 13 Lets take a quick look at the crosswalk set up by DPLA. Im going to go into this in more depth in another video this week, because our first assignment will be to create a crosswalk like this for a sample record. But to give you a quick overview, this is a crosswalk set up DPLA. It basically is like a translation of how metadata in other formats would be expressed using DPLAs application profile. So, if we look at the column for one of the DPLA partners, the Empire State Digital Network, who were the ones who published the record we just looked at, we see that it is like a series of equivalences ESDN expresses creator in this way, and that would correspond to how DPLA expresses creator as dc:creator. 14 So thats essentially what OAI doesit allows you to gather records from all over and put them into one database. The crosswalking and mapping step is another optional way that you can make them all the same for better searching though. The point of OAI is just to gather the records There are some pretty clear benefits to using OAI First of all, its pretty simple. Weve been looking at it in a very simple way, single HTTP requests through a browser, but there are tools out there to help set up a feed and harvest feeds and they are pretty easy to understand once you know some of the basic concepts. The other thing that we saw is that the protocol can be used to create tools to do harvests in an automated fashion. So you can configure a bit of software to do these requests and gather these records, and it will go and do it on its own, you dont have to deal with downloading say an export of all your files and manually sending them to an aggregator. And as an aggregator, I dont have to be involved in every single request. As we saw the OAI standard is flexible about metadata. It has its own very simple wrapper standard, but after that any metadata that is in XML can be posted. 15 Finally, OAI was developed in the early 2000s, and at this point it is widely adopted. Many repository services have OAI publishing as a standard part of their operation. Even our Omeka.net accounts we will set up for the final project allow us to harvest from OAI feeds. (its one of the plugins, check it out if you are interested). 15 Thats not to say that there arent drawbacks however. One that isnt too big of an issue, but which sometimes becomes a problem is the fact that we can only share metadata in xml formats. We cant, for example, send files of csv encoded data using this protocol. Another issue is with the time it takes to reharvest. OAI send a request over the web for records, typically in groups of no more than 500 at a time. While each request can only take milliseconds, as your provider grows, your harvests grow as well, taking up more and more time and resources to complete. If you amass collections of hundreds of thousands of records it could take more than 24 hours to complete depending on the speed of the server at your source, which you have no control over. As I mentioned earlier , there is also the problem of the data that we have becoming out of date. When I worked at DPLA we reharvested records from our partners typically four times a year. Any changes they make between harvests arent reflected in our data until a few months later when we harvest again. Luckily, its mostly a question of just not having new records added. The records themselves dont often change much, but if an item is removed from the source collection it could still have a record in the aggregation for several months.. 16 So OAI was one way to share metadata, and it involved sharing entire collections of records. Another way of sharing data that is a more modern technology is call Linked Open Data or LOD. It is another kind of interoperability and it really involves sharing discrete portions of data, rather than entire collections or sets. At this point, if you havent yet watched the video about linked data that was posted in the readings, you should stop this lecture and go and do that now. Im not going to cover linked data in as much depth, because the video does a pretty good job. 17 Assuming youve seen the video, Ill just reinforce a few concepts. The premise of linked data hinges on the idea that everything has an URI. So concepts like an LCSH controlled subject heading, or the entry for an authors name in an authority filethese would all have a identifying URI (same thing as a URL really with a few important differences, but those arent crucial for us to understand at this point). When you wanted to say something about that concept or thing, you would use the URI as a reference point. Think of URIs as just like an identifying number for a concept. There are rules about the technology used around URIs (that they are created according to the HTTP protocol, and that they are provided in a data encoding standard called RDF (not XML for example)). Then, you can create resources that combine URIs from different sources and anyone who wants to find something out about a concept can look for that URI in different sources. 18 One thing I thought the video didnt necessarily cover explicitly is where those URIs come from. Its not like some universal council sits down and decides what the URI for cat is. Instead what you have are lots of different data services that have vocabularies of terms or definitions. One example here is the Library of Congresss Name Authority File. LC has created a URI for each name in its file. So thats great, but then what if another organization has another URI for that name? 19 Well, if they say, like this LCNAF page does that their URI is the same thing as another sources URI, thats one way to link the two. Here at the top, we see that this LCNAF record states that their term for Edgar Allan Poe is exactly the same as this other term from VIAF (the Virtual International Authority File created by OCLC). So already weve joined the data here at the LC page, with the data over at VIAF. 20 Another way that things get linked is when another party comes along and reuses those URIs. This is some metadata from a theoretical authority record in a catalog. The original source record just said the name Poe. In our authority record, we are asserting that our author named Poe is the same as the Edgar Allan Poe named by LCSH, which is also the same as the entry for Edgar Allan Poe in VIAF. Now we have relationships between three data sources. 21 The neat thing about Linked Data is seeing what you can do once you have those URI identifiers in sources. The video we watched about linked data used information about edgar allan poe in google search results. So lets talk about how this would really work. First, google has recognized that my search term Edgar Allan Poe is something that has a URI reference in some different sources. Probably it has a list of such terms and kicks off this linked data tool when someone searches for them. Next Google has gone to a couple of sources to look for matches to edgar allan poe. First it looks like its gone to something like wikidata, which is a database of content from wikipedia put into linked data. So wikidata would have assigned a URI to edgar allan poe. Google can look up that uri and then use it to grab wikidatas information about poe while it is bringing you the results of your search. It looks like it also went to a book source, probably its own google books records. Now, why is this any different from searching by Poes name? Well, for one thing, using a single URI instead of a name gets around the problem of people writing the name in different ways. If one source said Poe, Edgar and another just said Poe, but they all used the same URI we can be sure that it really meant this Edgar Allan Poe. 22 Its a way of dis-ambiguating or exerting authority. The other thing that is a benefit here, is that linked data technology allows you to do this in real time if you want. So when you do the search, google can actually going out and pull that information dynamically and live from wikidata and elsewhere. So if you add another book, or update the information, it gets updated here as well, in realtime. This removes problems with synchronization and indexing. It might cause your application to be really slow though, so you might actually create a local cache of whats at the source and update it periodically instead. But the point is you have the ability. 22 Lets transition now to talk about quality. Issues of quality are really important when we want to share metadata. We read an article this week that talked about Shareable Metadata. That phrase was coined more than 10 years ago, and it that refers to thinking about your metadata in terms of not just the local community, but the global community. So when you are creating your metadata in your local context, you are also thinking about what it would look like if it was picked up and reused elsewhere. We learned from the Shreeves article that when thinking about the creation of metadata with sharing in mind we should think about these six cs Content: what information would it take to make this content understandable to anyone. Will someone from another country understand that a picture of LBJ is Lyndon Johnson or will they not recognize that acronym Consistency: refers to consistent use of similar forms of metadata values. For example, using the same controlled vocabulary throughout, or formatting dates or author names the same way throughout all records Coherence: means that records are self-explanatory and complete. A record shouldnt mix descriptions of different views of the object. For example, a record for a digitized image shouldnt include both the date of the original objects creation and 23 the date of the digitization in the metadata without distinguishing the different between them. Context: means that any information about context that is needed to make the record understandable outside of its original collection is explicitly included in the metadata. That could include information about a collection the item is a part of for example. Communication: relates to the actual interaction between those who own and organize collection and another organization it is sharing data with. You wont always be able to control this element, but when you can you should include all the relevant information like schema and vocabularies used, when the data was last updated, etc. Finally, Conformance to standards is key for sharing. Creating your own local standard may really suit your needs, but if no one else understands it, it wont be useful. As we mentioned application profiles can really help with this. 23 In addition to those concepts, we can also rely on different standards to ensure quality. Content standards give us directions for how to create values. Examples are how to format dates or author names, or when creating a title for an untitled item how to formulate that. Controlled vocabularies are lists of defined terminology for specific purposes. A lot of them involve subject headings (like LCSH or MeSH) but other are related to terms for formats, or authorized versions of names. In the linked data world we also have Data Endpoints, which are like linked data versions of controlled vocabularies You can put in an identifier for a term in the vocabulary and you can write code in your web interface that will go and look up the term. The benefit is that if the term is updated, what you display is always updated. Or if you want to have an option to display the interface in a different language, if the end point includes variations of the term in different languages, you can do that automatically. This is a core concept of Linked Open Data. Ill post a supplementary video this week with an example of using a Linked Data endpoint to add some data to a spreadsheet. So some examples of endpoints are the virtual international authority file (for persons names), id.loc.gov which holds all of the library of congress authorities, and 24 geonames is a particular geographical endpoint. 24 So how about we look at an example of both of these technologies in the wild. My previous employer, DPLA, uses both OAI and Linked Data --as an aside, youll hear people say both Linked Open Data and Linked Data. When the word open is used it connotes linked data that is freely available to all. Not all linked data is open, some are subscription services. Just as a side point Anyway 25 At DPLA we aggregated metadata from more than 40 hubs, representing about 3,000 individual institutions and aggregated more than 30 million records. We received metadata in 9 different schemas, including major standards as well as product-and institution-specific profiles, and several are not in an XML format. We harvest records from OAI feeds, APIs, and through submitted data files, and many of these records have already been aggregated by one of our hubs. We built our own customized tools for OAI harvesting, metadata mapping and metadata remediation because we need to work on it at such a large scale. 26 Once we had the partners source records we mapped that data to make a record that adheres to the DPLA metadata application profile according to our crosswalks (remember we looked at that back at the beginning of the lecture). We also added to our records URIs for some of the terms in the records if we can make a match for them, particularly the types from the Dublin Core type list (things like image, text, video, etc.) as well as geographical names in the Geonames vocabularly We didnt add URIs for things like subjects or name authorities yet, but if the source records do have those URIs we could store them in our record as well. We were working on plans to enrich records with those URIs in the future. 27 With one particular type of URI we were enriching records with data from an endpoint. In this record, the text and the icon for rights status comes from a linked data endpoint. The original record only contains the URI for a rights statement, which is outlined in red here. Thats what the underlying metadata record for this object (or a part of the record) looks like (this is a different format than XML, by the way, this format is called JSON). But the way weve written the code for the web-displayed version shows the full statement label and description which comes from a website called rightsstatements.org (well be learning more about this later, by the way). Right now the statements are available in other languages, so we could create an alternate language version of the site that would use a specific language instead. It will also automatically update if the descriptions get modified or the icons change. 28 So thats it for metadata part two. I hope this wasnt too mind-blowing. I know the linked data stuff can be hard to grasp at first. Metadata is pretty cool and pretty powerful. I think the key thing to keep in mind is that metadata should be consistent and as understandable as possible to make it the most useful if it gets aggregated or re-used. 29 This week we have our first assignment. Ill be posting a demo of me working on a crosswalk that will help you with that. It will be due on the 28th Next week well bring our objects and metadata together into a digital repository. As usual, you also have a forum question available to you this week. 30 ...
- Créateur:
- Gretchen Gueguen
- La description:
- Second part of two week unit on metadata, covering application profiles, metadata crosswalks, metadata aggregation methods (OAI-PMH and federated searching), and linked data.
- Type:
- Text
- Type de ressource d'apprentissage:
- Lecture notes
- iveau d'éducation:
- Graduate / Professional
- Public:
- Instructor
-
- Correspondances de mots clés:
- ... Platos Republic An Introduction SEAN MCALEER PLATOS REPUBLIC Platos Republic An Introduction Sean McAleer https://www.openbookpublishers.com 2020 Sean McAleer This work is licensed under a Creative Commons Attribution 4.0 International license (CC BY 4.0). This license allows you to share, copy, distribute and transmit the text; to adapt the text and to make commercial use of the text providing attribution is made to the authors (but not in any way that suggests that they endorse you or your use of the work). Attribution should include the following information: Sean McAleer, Platos Republic: An Introduction (Cambridge, UK: Open Book Publishers, 2020), https://doi.org/10.11647/OBP.0229 In order to access detailed and updated information on the license, please visit, https:// doi.org/10.11647/OBP.0229#copyright Further details about CC BY licenses are available at https://creativecommons.org/ licenses/by/4.0/ All external links were active at the time of publication unless otherwise stated and have been archived via the Internet Archive Wayback Machine at https://archive.org/web Updated digital material and resources associated with this volume are available at https://doi.org/10.11647/OBP.0229#resources Every effort has been made to identify and contact copyright holders and any omission or error will be corrected if notification is made to the publisher. ISBN Paperback: 9781800640535 ISBN Hardback: 9781800640542 ISBN Digital (PDF): 9781800640559 ISBN Digital ebook (epub): 9781800640566 ISBN Digital ebook (mobi): 9781800640573 ISBN XML: 9781800640580 DOI: 10.11647/OBP.0229 Cover image: Anselm Feuerbach, The Symposium (1873). Berlin State Museum, Wikimedia, https://commons.wikimedia.org/wiki/File:Anselm_Feuerbach_-_Das_Gastmahl._Nach_ Platon_(zweite_Fassung)_-_Google_Art_Project.jpg. Public domain. Cover design by Anna Gatti. Table of Contents Acknowledgments vii Introduction xiii 1. Fathers and Sons 1 2. Taming the Beast: Socrates versus Thrasymachus 25 3. A Fresh Start 55 4. Blueprints for a Platonic Utopia: Education and Culture 75 5. Starting to Answer the First Question: The Political Virtues 93 6. The Republics First Question Answered at Last: Personal Justice 113 7. Questions about the Idea Polis: The Three Waves 131 8. Surfing the Third Wave: Platos Metaphysical Elevator, the Powers Argument, and the Infallibility of Knowledge 151 9. The Philosophers Virtues 175 10. Metaphors to Think by: The Sun and Divided Line Analogies 191 11. The Allegory of the Cave 211 12. The Decline and Fall of the Ideal City-Soul 229 13. The Republics Second Question Answered: Three and a Half Arguments that the Just Life is Happier 251 14. Are We There Yet? Tying up Loose Ends in Book X 275 Afterword 299 List of Illustrations 305 vi Platos Republic: An Introduction Bibliography 309 Index 313 Acknowledgments This book springs from the happy confluence of two sources: my teaching the Republic every semester in PHIL 101 at the University of WisconsinEau Claire and my offering a three-session class on the Republic to Chippewa Valley Learning in Retirement in the fall of 2013. Dr Mike OHalloran, the indefatigably cheerful and intellectually curious retiree who thought the group would enjoy a presentation on philosophy turned out to be correct: the sessions were well attended and well receivedif subsequent requests for more philosophy sessions are any indication. Although some philosophical friends were skeptical at my plan to devote an entire intro course to the Republic, many students seem to have found the experience worthwhile, so I have continued with this somewhat old-fashioned way of introducing students to philosophy. This book has been shaped by my experience with both kinds of audiences. I thank the students it has been my privilege to teach over the years and the CVLR audiences for their questions, feedback, criticisms, and their laughing at some of my jokes. Many friends have helped in a variety of ways. Erica Benson, the life partner than which none greater could be conceived, provided insightful feedback on the entire manuscript, created the figures for the Divided Line, and talked me off the ledge more than once. Geoff Gorham has used parts of the manuscript in some of his courses and has given feedback and encouragement, as has his wife, the philosopher Amy Ihlan. Rod Cooke unwittingly served as a responsibility buddy during a sabbatical, regularly asking me how it was going and when it might it be finished. My colleagues at UWEau ClaireKristin Schaupp, Matt Meyer, and Steve Finkmodels of collegiality all, have been sources viii Platos Republic: An Introduction of intellectual stimulation and delight during trying times in higher education. I gratefully acknowledge the support of the University of WisconsinEau Claire Faculty Sabbatical Leave Program, which supported me during the 20172018 academic year, during which time the bulk of this book was written. I conceived the book as a philosophical instance of The Wisconsin Idea, a guiding principle of the University of Wisconsin system, which bids faculty and staff to extend knowledge and its application beyond the boundaries of its campus. I have tried to do that here, to help general readers with little to no background in philosophy to understand this philosophical masterpiece. Thus I am most grateful to Open Book Publishers for publishing it, since I too believe that knowledge is for sharing. I thank Alessandra Tosi for her wisdom, guidance, and patience; the two readers for their helpful suggestions, Anna Gatti for designing the cover; and Melissa Purkiss for her careful proofreading and her excellent editorial judgment. I have benefitted from some wonderful teachers over the years, starting in high school with Frank Townsend, who gave me my first glimpse of the life of the mind, continuing through my undergraduate education at Shimer College with Eileen Buchanan and Harold Stone, who provided such fine, living models of inquiry and engaged classrooms, and lastly in graduate school at Syracuse, where Michael Stocker and Jonathan Bennett showed me what doing excellent philosophy looks like. I am grateful to them all, and to all the other fine teachers I havent space to name individually. I thank Hackett Publishing for their kind permission to quote so frequently from the Grube-Reeve translation of the Republic. Lastly, I thank the Office of Research and Sponsored Programs at UW-Eau Claire for financial assistance with the publication of this book. It is a good light, then, for those That know the ultimate Plato, Tranquillizing with this jewel The torments of confusion. Wallace Stevens, Homunculus et La Belle toile For Erica, my SLPF Attic Greek Black-figure Neck Amphora attributed to the Princeton Painter, ca. 550540 BCE depicting an elderly king or man seated between two men and two women. Photograph by Aisha Abdel (2018), Wikimedia, Pulic Domain, https://commons.wikimedia.org/wiki/ File:Terracotta_neck-amphora_of_Panathenaic_shape_(jar)_MET_ DP161828_white_balanced_white_bg.png Introduction Platos Republic is one of those books that most people have probably heard of, even if they have not actually read it. Even Bubbles, the goodhearted, bespectacled doofus of the long-running Canadian comedy Trailer Park Boys knows enough of the Republic to appeal to the famous Noble Lie in a conversation with another resident of Sunnyvale Trailer Park. I first encountered the Republic like so many others have: in my first semester of college. This was many years ago, but my memory of the experience was one of feeling lost much of the time. I had a fine high school education, but philosophy was new to me, with its focus on big, abstract questions and especially on rigorous, rational arguments as the means to answering them. I did reasonably well in the course, but the Republic was tricky terrain, and I did not really know my way about. My aim in this book is to help readers traverse Platos philosophical masterpiece with fewer falls and less befuddled wandering than I experienced. I try to do this by pointing out important landmarks and interesting bits of topography, helping readers not to miss the forest for the trees, as the saying goes, but also to appreciate the importance of particular trees, hills, and streams. I consider objections to the views and arguments Plato has Socrates express and make. Thinking philosophically requires, among other things, stating arguments clearly and carefully, articulating assumptions that lurk in the background, and making judgmentshopefully, good judgmentsabout whether the reasons offered in support of a claim are good reasons. Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.16 xiv Platos Republic: An Introduction The Republics Two Main Questions The Republic addresses two overarching questions, What is justice? and Is a just life happiermore profitable or personally advantageous than an unjust life? Plato addresses these questions in what is for modern readers an unexpected way: in dialogue form. Instead of writing an essay or a treatise directly arguing for his view, he gives us a philosophical drama, so to speak, a conversation between Socrates and several others in which answers are offered, discussed, and typically rejected. Plato wrote almost all of his philosophy as dialogues, most of them featuring Socrates talking with someone he would encounter in Athens (though Platos later dialogues no longer feature Socrates). Plato was not Socrates student in a formal sense, since Socrates himself wrote nothing and started no schoolunlike Plato, who founded the Academy, where Aristotle studied before founding his own school, the Lyceum. But like many young men of his day, Plato was taken with Socrates, struck by his sharp and open mind and his fearless but often failed pursuit of knowledge. Whether the views the character Socrates expresses in the Republic are his own or whether Plato uses him to express his own views is an interesting issue, but it is not one that we need worry over to come to terms with the Republic. I will usually make no distinction between Plato and Socrates in this book, except when doing so helps our understanding, as when, for example, Socrates seems to make an error in reasoning or allows a crucial assumption to pass unquestioned. Is the mistake one that Plato himself does not recognize? Or does he intentionally have Socrates stumble or pull a fast one because this is what actually happened in the conversation, of which the dialogue is a faithful but stylized representation? Ormore likely, I thinkbecause he wants us, his readers, to engage in imaginary dialogue with Socrates, to raise objections and questions where the other characters are silent or too agreeable? That Plato writes philosophy in dialogue-form complicates the life of the reader, but it is a complication that is rich and rewarding, and also enables Plato to manifest respect for his readers. His aim is not the transmission of truth or doctrine from the knowing sage to a passive but receptive learnerindeed, in presenting the famous Allegory of the Cave he explicitly rejects the idea that education is putting knowledge into souls that lack it, like putting sight into blind Introduction xv eyes (7.518b).1 Instead, we are expected to be active, engaged readers who wrestle with the questions and arguments for ourselves. Writing dialogues suggests that philosophywhich I take to be clear, rigorous thinking about those important questions that are outside the ambit of the natural or social sciencesis best done in conversation with others rather than alone in ones study. Readers with some familiarity with philosophy will not be surprised that one of our first tasks in trying to understand how Plato has Socrates answer the Republics two main questions is to question the questions themselves. What exactly does Plato mean when he asks about the nature of justice and whether it is more profitable than injustice? An important point straightaway is that (dikaiosun), which is translated as justice, can have broader meaning than the English word justice has, which typically involves fair distributions or the idea of rights. Dikaiosun certainly has this narrower sense too; in Book V of his Nicomachean Ethics, Platos student Aristotle distinguishes between specific and general senses of justice, where specific justice concerns what today we would call distributive justice (which asks whether a particular distribution of goods is fair) and retributive justice (which asks if and how wrongdoers should be punished). The broader sense that Plato has in mind connotes moral goodness more generally, a virtue of doing the right thing (though we will ultimately see that for Plato justice is primarily about being a certain sort of person rather than doing certain kinds of things). Justice in this broad sense might be rendered by righteousness, but that seems rather archaic and can have misleading religious connotations. Aristotle suggests that justice in this general sense is complete virtue, the whole of virtue, of which the narrower kind of justice is a part.2 When Socrates asks what justice is, he is asking 1 I will cite the Republic in this way. 7.518b means that the passage quoted is in Book VII of the Republic at page 518 in the standard Greek text of Platos work, section b (about one-fifth of the way down that page). Thus, regardless of which translation readers have before them, we can all quite literally be on the same page, so long as the translation provides the Stephanus numbersnamed after a sixteenthcentury editor of Platos worksin the margins. I will quote from G.M.A. Grubes translation, as revised by C.D.C. Reeve (Indianapolis: Hackett Publishing, 1992), which is excellent and inexpensive. 2 Nicomachean Ethics, trans. by W. D. Ross and rev. by J. O. Urmson, in The Complete Works of Aristotle (Revised Oxford Translation), ed. by Jonathan Barnes (Princeton: Princeton University Press, 1984), p. 1783 [Book V, Chapter 1, Bekker page 1129b25]. xvi Platos Republic: An Introduction about the nature of moral goodness generally, asking what is it to be a good person. The Republics second question asks whether being a good person makes one personally better offwhether it would make living most worthwhile for each of us (1.344e). There is no question of whether a just life is a morally better than an unjust life; the issue the second question raises, by contrast, is whether a just life is prudentially better, as philosophers often put itwhether it is in ones interest to be just and act justly. This question has great practical importance, given the overwhelmingly plausible assumption that each of us wants to be happy. As Socrates puts it, the argument concerns no ordinary topic but the way we ought to live (1.352d). In ordinary English there is a subtle distinction between leading a good life and having a good life. At the funeral of a friend who was devoted to the wellbeing of others we expect the eulogy to focus on the former: they led a good life, helping others without thought of self and often to their own detriment. At the funeral of a friend devoted to the pleasures of the table and the bedroom we are likelier to hear that they had a good life. So the Republics second question inquires about the connection between leading a good life and having a good life. It is a comparative question, asking if the just person is happier than the unjust person. Socrates is not arguing that justice is sufficient for happiness, that being just alone makes for a happy life. Instead, he will argue that justice is necessary for happiness, that we cannot be happy without being just. Socrates thinks that justice alone will not guarantee happiness, since there may be external circumstances that make happiness impossible, even for the just person. But the just or morally good person will be as happy as it is possible to be in those circumstances and always be happier than the unjust person, since justice always makes one better off than injustice, he thinks. As we follow along, it will be helpful to bear in mind ways in which happiness can be a misleading translation for the Greek word (eudaimonia), which connotes flourishing or thriving, something deeper and longer lasting than the perhaps fleeting psychological state of enjoyment that we might associate with our word happiness. A flourishing person All translations of Aristotle will be drawn from The Complete Works and will be cited by title, book and chapter, and Bekker page (the Aristotelian analog of the Platonic Stephanus numbers), thus: Aristotle, Nicomachean Ethics, V.1 1129b25. Introduction xvii will typically enjoy their life, but the enjoyment is best thought of as a by-product of happiness rather than its essence. The Structure of the Republic The Republics two main questions give it its structure, which I sketch here: Book I introduces but ultimately fails to answer the Republics two main questions. Socrates discusses the nature and value of justice first with Cephalus and Polemarchus and then with Thrasymachus, a more sophisticated and less friendly interlocutor. Socrates initially thinks that he has refuted Thrasymachus view that the unjust life is happier than the just life, but he soon realizes that he has left the Republics first question unanswered and thus that he has not really answered the second question; how could he know which life is happier if he does not yet know what justice is? Books IIIV answer the Republics first question, What is justice?. Socrates young friends Glaucon and Adeimantus (who in real life are Platos brothers) challenge Socrates to continue after the failure of Book I. They agree with him that the just life is happier than the unjust life, but they recognize that they cannot justify their view and thus do not really know that the just life is more profitable. They press Socrates to forgo the rapid-fire argumentation of Book I and to offer a more intuitive, accessible way of answering the Republics questions. Although these questions concern justice as a virtue of persons (which well call personal justice), Socrates suggests that, since a polis (a Greek city-state) is just like a person, only bigger, the best way to figure out the nature of personal justice is to investigate justice in the polis (political justice) since it will be easier to find justice in the larger thing. Thus they set out to theoretically construct an ideal polis, which is completed by the end of Book III. And by the end of Book IV, Socrates thinks he has answered the first question and starts on the second. In Books VVII, Socrates answers questions about and objections to his answer to the Republics first question. These are dubbed the Three Waves, since they threaten to destroy the ideal city. The First Wave concerns whether women can be rulers in the ideal polis. Socrates view on this might surprise you. The second addresses the ideal citys xviii Platos Republic: An Introduction communal life, especially how children are to be raisedwhich seems to do away with the traditional family. The third and most threatening concerns the ideal polis itself: is their ideal city merely theoretical, or could it be realized in the actual world? Socrates thinks such a city can be realized only if it is ruled by philosophers, which leads to an investigation of what a philosopher is. This investigation will last through Book VII. In addressing the Third Wave, Plato has Socrates introduce the famous theory of the Forms and offer one of the Republics central arguments, the Powers Argument, in defense of this view; he presents the analogies of the Sun and the Divided Line in Book VI, and the famous Allegory of the Cave in Book VII, among other things. Having addressed the Three Waves to the companys satisfaction, in Books VIII-IX Socrates turns to the Republics second question, Is the just life happier than the unjust life?. Expanding on the psychology and political philosophy developed earlier, he distinguishes between five possible kinds of souls and city-states and argues that the just life is happier than the unjust life. Having answered the Republics two questions, in Book X Socrates returns to the status of poetry, which featured prominently in the educational program sketched in Books II and III. Despite his love for poetry, especially the works of Homer, he argues that most poetry should not be allowed in the ideal city because of its power to corrupt us. He concludes with the intriguing Myth of Er, about the importance of choice in a happy, well-lived life. Readers will often find it helpful to keep the Republics overall structure in mind while making their way through the text, since what a character is talking about often makes more sense when we understand why they are talking about it. So it can be helpful, when feeling a little lost, to orient oneself by asking which question of the Republics two main questions is being addressedalthough it might take a bit of intellectual sleuthing to determine that. For example, the details of the educational program Socrates develops in Books II and III are interesting in their own right, but it is easy to lose sight of why he devotes so much time and intellectual energy to this topic. If we keep the Republics overall structure in mind, we can see that Socrates discusses education and culture because he is exploring what an ideal polis is like, which requires an understanding of how the poliss rulers will be Introduction xix educated. And of course, he wants to create this ideal polis because the plan is to define political justice in order to define personal justice. And while the Republics first question about the nature of personal justice is interesting in its own right, Socrates wants to answer it because, as he realizes at the end of Book I, we cannot satisfactorily answer the Republics second question about whether the just life is happier until we know what justice is. As orienting oneself by overall structure is an aid to understanding, I will try to offer signposts and reminders as we proceed through the Republic. Shortly I will offer more detail about what individual chapters of this book will contain, but before doing that I want to draw the readers attention to one more big-picture topic. Arguing about Justice Thrasymachus, Socrates main antagonist in the second half of Book I, thinks that justice and happiness are at odds with each other, that being just and acting justly leave one worse off. Socrates disagrees, and it is instructive to see what he does and does not do in the face of this disagreement. First, what he does not do: he does not insult Thrasymachus or impugn his intelligence or his motives. Sadly, the same cannot be said for Thrasymachus, who responds to Socrates arguments in a rather nasty way. Nor does Socrates shrug and say things like, Everyones got a right to their opinion, I guess or Whos to say? or Thats just your opinion, man, like a Lebowski of classical antiquity who has traded his bathrobe for a chiton (the ancient Greeks did not wear togas; that was a Roman thing). Socrates does not think that reason merely sheds light on the Republics main questions, he thinks it can answer them. Some readers will be less confident in the power of rational argument and conceptual clarity; they may be more comfortable than Socrates and Plato are with there being more than one correct answer to these questionsor with there being none. But even though Socrates himself is not a moral pluralist, it is important to see that the method he employs in arguing against Thrasymachus is consistent with there being a plurality of answers to moral questions of the sort that the Republic devotes itself to. For while Socrates method of question-and-answerformally called elenchus, a kind of xx Platos Republic: An Introduction cross-examinationis impersonal in the sense of focusing on principles rather than personalities, it is in another sense profoundly personal, for its focus is what the person he is engaging with thinks. The best way to investigate the nature of justice, he thinks, is to critically examine the views of someone who claims to know what justice is, to see if such a view can survive rigorous cross-examination and coherently hang together. So he proceeds from premises that his interlocutors endorse. Although Socrates thinks that there is an Archimedean point from which one can definitively settle moral questions, the Socratic method of question-and-answer does not presuppose this exalted view of reason. Its aim is more modest: to discover whether ones philosophical and moral beliefs are internally consistent. While this method is no respecter of persons in that it does not defer to someone based upon their social class, etc., it is, I think, profoundly respectful of persons, since it takes seriously a persons moral and philosophical views. Even though these views are usually found wanting, a willingness to examine a persons views about the nature of justice or courage or knowledge or whatever is certainly a way of taking those views, and that person, seriously. What to Expect in this Book This book is not a line-by-line commentary of the Republic, but it hews closely to the main contours of the Republic. I intend it as an aid to reading the Republic rather than as a substitute for doing so. In the chapters to come I try to guide readers, especially those new to the Republic or returning to it after a long absence, to a clear understanding of the Republics main themes and distinctive arguments. But we will also pause to linger over details that are interesting in themselves and which contribute to a nuanced understanding of Platos philosophical thought and literary artistry. I will try to clearly and accurately spell out the arguments Plato has Socrates offer and then critically reflect on them, asking questions such as Does the conclusion logically follow from the premises? and Do we have good reasons to think the premises are true? and What assumptions are driving the argument?, etc. We will see that Socrates interlocutors often accept arguments that they have good reason to doubt. This is something most of us do, especially when we think the conclusion is true, but setting aside ones belief in a Introduction xxi conclusion and querying the quality of the reasons offered in support of it is the hallmark of good critical thinking. I will try to model that in the pages to come and hopefully help readers sharpen their own philosophical skills. Since one of Platos aims is for us, his readers, to think philosophically for ourselves, nothing would delight me more than readers disagreeing with and arguing against claims, interpretations, and assessments I make. Needless to say, there is a lot I will leave out as we proceed through the Republic, but by the end readers should have a good sense of the main themes and arguments of the Republic and of some of the philosophical problems with them. Here is a chapter-bychapter rundown of the main issues to be discussed. Chapter One, Fathers and Sons, covers the first half of Book I of the Republic, where Socrates raises the Republics first question about the nature of justice at the home of Cephalus, a wealthy merchant who lives in a suburb of Athens. Cephalus suggests that justice is paying ones debts and telling the truth, but Socrates thinks this cannot be the essence of justice, since there are times when one should not return what one has borrowed. This alerts us to an important fact about what Socrates is looking for in an account of justice: the account should be unconditionally correct, with no ifs, ands, or buts. Cephalus son Polemarchus jumps into the conversation and offers a revision of his fathers definition, suggesting that justiceright conduct, generallyis benefiting ones friends and harming ones enemies. Socrates finds this account has implications that Polemarchus himself cannot accept, so the chapter explores Socrates reasoning, especially the assumption that justice, a virtue of character, is a craft or skill. We then discuss Socrates more direct argument against Polemarchus account, that the just person would not harm anyone. Chapter Two, Taming the Beast: Socrates versus Thrasymachus, is devoted to Socrates encounter with the sophist Thrasymachus in the second half of Book I. Thrasymachus answers to the Republics main questions are a provocative challenge to the reverential attitude Socrates has toward justice in particular and virtue in general. Thrasymachus defines justice as whatever benefits the politically powerful and argues that a conventionally just person lives less happily than their unjust counterpart. Socrates offers five different arguments against Thrasymachus views, which are spelled out clearly and evaluated xxii Platos Republic: An Introduction carefully, with attention paid to the connections between them and to the crucial concepts around which they orbit (e.g., the notion of a virtue). Socrates arguments fall short of the mark, and we will examine why this is the case, exploring avenues of response that Thrasymachus could but does not take. By the close of Book I, Socrates realizes that he has not answered the Republics second question because he has not yet answered the first: we cannot know whether the just life is happier until we first know what justice is. Chapter Three, A Fresh Start, explores the way in which Socrates tries to address the Republics two questions, What is justice? and Is the just life happier than the unjust life?. Rather than offering a battery of arguments as he did in Book I, Socrates offers an analogy between the polis (the Greek city-state) and the psych (individual soul) that will structure the rest of the Republic. The plan is to first discover the nature of justice as a political virtueas a virtue of the polisand then apply this to the individual soul in order to discover the nature of personal justice. Chapter Four, Blueprints for a Platonic Utopia: Education and Culture, examines Socrates account of education in the ideal polis, focusing especially on informal, cultural education in music and poetry. We will explore the fascinating connections Socrates draws between aesthetic and moral development, especially the role that poetic and musical style play over and above content. We then discuss Socrates rather disturbing attitude toward disabled citizens before focusing on the famous Noble Falsehood, which concludes Book III, discussing the role that myth, especially myths of origin, play in civic self-understanding. Chapter Five, Starting to Answer the First Question: The Political Virtues, focuses on the first third of Book IV. The ideal polis complete, Socrates and company investigate the political virtues of wisdom, courage, moderation, and justice, defining each and discussing their location in the polis. We will explore these accounts and the issues they raise, for example how the kind of agreement that constitutes political moderation differs from the idea of consent in modern liberal political thought, and the question of whether there are other virtues in addition to the four cardinal virtues. We continue discussing Book IV of the Republic in Chapter Six, The Republics First Question Answered at Last: Personal Justice. We first Introduction xxiii attend to Platos foray into psychology (literally, his account (logos) of the soul (psuch)) in which he tries to justify the analogy between city and soul that has shaped the Republic. By appealing to the idea that the same thing cannot simultaneously undergo or perform opposite states or activities (dubbed the Opposition Principle), Socrates argues that the soul has a three-part structure, just as the city does: a rational part, which corresponds to the guardian-rulers in the polis; a spirited part (the seat of anger and pride), which corresponds to the soldierly auxiliaries of the polis; and an appetitive part, which corresponds to the craftspeople. Socrates then derives the personal virtues by applying the political virtues to the soul. The most important personal virtue, of course, is justice, which he conceives of as each part of the soul doing its own work: reason, not appetite or spirit, governs the just soul. We will pay attention to important features of this account, for example how it differs from Cephalus and Polemarchus, for whom justice is a matter of interpersonal, external doing (of how one treats ones fellows), while for Socrates and Plato is it a matter of intrapersonal, internal being, of what ones soul is like. In Chapter Seven, Questions about the Ideal Polis: The Three Waves, we see Polemarchus and Adeimantus begin Book V by putting the brakes on Socrates attempt to immediately begin answering the Republics second question, whether living a morally good life is good for the person living it. They raise questions about and objections to the ideal polis, known as the Three Waves, which is an apt metaphor for a sea-faring culture. The First Wave concerns the question of whether women can be guardian-rulers in the ideal city. Socrates affirmative answersurprising to his companions and to many readers alike (though for different reasons)raises the question of whether Plato is a feminist. The Second Wave concerns the ideal citys communal living arrangements, especially child-rearing. Socrates argues that not only is the abolition of the traditional family possible, it is beneficial. The Third Wave is the subject of the next chapter. Chapter Eight, Surfing the Third Wave: Platos Metaphysical Elevator, the Powers Argument, and the Infallibility of Knowledge, focuses on the Third Wave, which concerns the very possibility of the ideal city. Socrates famously claims that the ideal city can be made real only if philosophers rule. This leads him to explore how philosophers xxiv Platos Republic: An Introduction differ from non-philosophers, which will guide the last part of Book V as well as Books VI and VII. A crucial point of difference is that philosophers have knowledge while non-philosophers merely have belief, a distinction which is explored in some depth and detail. We devote special attention to one of the Republics most crucial arguments, the Powers Argument, in which Socrates argues for the existence of the Forms, the mind-independently real, timeless essences of the many particular things that populate the everyday world of our senses. The reality of the Forms is perhaps Platos most distinctive metaphysical view, so we devote quite a bit of attention to stating, explaining, and evaluating the Powers Argument, and to discussing the implications of its being seriously flawed. Chapter Nine, The Philosophers Virtues, continues to explore the distinction between philosophers and non-philosophers, focusing on their different characters. Central to the discussion is the distinction between virtues of character (for example, justice), intellectual virtues (for example, a good memory), and virtues of personal style (for example, grace and elegance), attending to the light this last category sheds on Platos moral vision. As a prelude to the key analogies of Book VI, the rest of this chapter is devoted to the interesting analogies Socrates appeals to in addressing features of the Third Wave. Chapter Ten, Metaphors to Think By: The Sun and Divided Line Analogies, is devoted to the marquee analogies of Book VI, both of which address the Third Wave by developing the distinction between the sensible world of concrete particular things and the intelligible world of the Forms. Having suggested that the Form of the good is even more important than justice, Socrates cannot or will not say what the good is, but he does say what he thinks it is like: the good plays the same role in the intelligible world as the sun plays in the visible world. In the Analogy of the Divided Line, Socrates further develops the distinction between belief, which is appropriate to the sensible, visible world, and knowledge, which is appropriate to the intelligible world of the Forms. By exploring the role that hypotheses play in reasoning, he distinguishes philosophical knowledge from mathematical knowledge, somewhat surprisingly taking the former to be more rigorous. True to its name, Chapter Eleven, Shedding Light on the Allegory of the Cave, devotes itself to exploring the famous Allegory of the Introduction xxv Cave from Book VII of the Republic, carefully considering its various stages and themes before examining the issue posed by the enlightened philosophers return to the Cave. As Socrates describes it, the enlightened philosopher descends back into the Cave not because they want to, but because they recognize that justice requires them to do so. This raises an issue for discussion that Socrates does not seem to notice: the enlightened philosopher would be happier if they ignored the demands of justice and remained in the intelligible world of the Forms, which suggests that, contrary to Socrates view, the just life is not happier than the unjust life. In Chapter Twelve, The Decline and Fall of the Ideal City-Soul, we begin exploring Socrates answer to the Republics second question. In Books VIII and IX, Socrates sketches five kinds of cities and souls, noting what each takes as its primary end or goal and which part or class governs the soul and city, respectively. We trace the decay from the best city-soul to the worst, attending to the role that changes to education play and to interesting features of each stage, and discuss at some length Platos distinction between necessary and unnecessary desires. Chapter Thirteen, The Republics Second Question Answered: Three and a Half Arguments that the Just Life is Happier, explores the arguments Socrates gives in Book IX that the just life is happierindeed, 729 times happierthan the unjust life. There are fascinating features of the first two arguments, for example that the tyrannical person is incapable of friendship and that each part of the soul has a distinctive kind of pleasure. The third argument, the Metaphysics of Pleasure Argument, argues that since what is more filling is more pleasant and what is more real is more filling, the Forms, being the most real things, ground the most pleasant pleasures. We discuss this argument at some length, noting its dependence on the Powers Argument but also exploring ways in which Socrates seems to anticipate and preemptively respond to objections. In the last argument, which Socrates does not identify as such (hence the half), is a metaphorical argument which, despite its being less philosophically rigorous than the Metaphysics of Pleasure Argument, is more intuitively persuasive and in no way relies on the problematic Powers Argument. This chapter concludes with a discussion of Platos paternalism: his view that most of us, being incapable of the philosophical wisdom that consists of knowledge of xxvi Platos Republic: An Introduction the good, are incapable of good self-governance, so we are all better off being governed by someone elses (i.e., a philosopher-kings or -queens) reason. Chapter Fourteen, Are We There Yet? Tying up Loose Ends in Book X, explores the three topics of the Republics final book, Book X. The first is the status of poetry, which Socrates wants to revisit since he now has a psychology (the three-part soul) that he lacked when poetry was first discussed. He concludes, quite reluctantly, that very little poetry will be allowed in the ideal city, mainly because of its power to corrupt us: we give ourselves over to emotion and thus dethrone reason from its rightful place. After exploring his arguments for this view, we turn to his argument for the immortality of the soul, which Socrates offers in the context of showing the external advantages of living a just life (namely, having a reputation for justice), which were set aside to answer Glaucons and Adeimantus challenge of showing that justice was intrinsically goodthat all by itself it made its possessor better off. Lastly, we attend to the Myth of Er, with which the Republic ends. Ers story is an allegory about the importance of careful choice in living justly and thus happily. It is a fascinating way to end the Republic, in terms of both content and style; we briefly explore what philosophical points Plato might be making by ending a work of philosophy this way. Needless to say, I have not mentioned everything we will discuss, but this should give readers a good sense of the main contours of the Republic and a decent idea of what is to come. Now, on to the Republic! Theodoor van Thulden, Telemachus and Ulysses Meet in Eumaeus Hut (16321633). Photograph by Mr. Nostalgic (2019), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/File:Odysseus_en_ Telemachus_in_de_hut_van_Eumaeus_De_werken_van_Odysseus_ (serietitel),_RP-P-OB-66.764.jpg 1. Fathers and Sons: Book I Plato packs a lot into the Republics first book, so we will have an easier time of it if we break the discussion into two chapters. In this chapter we will examine Socrates conversations with Cephalus and then with Cephalus son, Polemarchus. In the next chapter we will explore Socrates encounter with Thrasymachus. The ever-curious Socrates wants to know what justice is not simply for its own sake but to determine whether a just lifea morally good lifeis happier than an unjust one. As mentioned in the Introduction, the Greek word (dikaiosun) is broader in meaning than the English word justice, which often suggests fair distributions or the idea of rights. I will continue to use it, but I will often also use synonyms such as right and moral goodness and their ilk. Righteousness seems a bit archaic and can have religious connotations that can be misleading. It is often thought that Book I of the Republic was initially a standalone dialogue as it ends, like so many of Platos other dialogues do, without an answer to its central question. Most of these dialogues have Socrates asking, What is ____? where an important notion like justice, knowledge, or courage fills in the blank. Socrates examines the answers his companions propose but typically finds them wanting, usually because they conflict with other beliefs held by the interlocutor. While not knowing what something is can be frustrating, knowing what it is not is often a helpful kind of knowledge, as it narrows the field and leaves us a bit closer to knowing what the thinghere, justiceis. Though Book I ends without a satisfactory answer to its central question, rather Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.01 2 Platos Republic: An Introduction than the discussants going their separate ways, as usually happens in Platos dialogues, two of the participants, Glaucon and Adeimantus (Platos real-life brothers) insist that Socrates continues, that he shares his beliefs about the nature and value of justice, even if he cannot in good conscience claim to know its nature and value. Polemarchus Wants You to Wait (1.327a328c) One of the many rewards of reading Plato is the literary quality of the dialogues, which are extraordinarily well crafted. That Plato writes dialogues rather than straightforward essays suggests that he regards philosophy as essentially conversational, that it involves back-andforth, give-and-take, that two (or three) heads are better than one when addressing philosophical topics like the nature of justice. The dialogue form also invites us to be active rather than passive readers, to engage in the dialogue by thinking of responses and questions that the people on the page do not make. In addition to Platos making a philosophical point by writing in dialogue form, his writing this way allows him to raise themes and issues that are at work in the background, where the conversation he is depicting is in the foreground. The opening lines of the Republic are an excellent example of this. The Republic is Socrates first-person account of a long conversation about the nature and value of justice that he has at the house of Cephalus, a wealthy merchant who lives in the Piraeus, the port of Athens. Platos situating the conversation outside of Athens might be his way of suggesting that the ideal city Socrates and his friends will imaginatively construct is an alternative to Athens; he is not offering suggestions for ways in which Athens might change for the better but instead offers a different political arrangement entirely. It is worth noting that the Republic is written around 380 bce, in the shadow of Athens defeat in the Peloponnesian War about twenty years previously. The conversation depicted takes place well before that, though scholars disagree about the dialogues dramatic date. One likely candidate is 421 bce, during the optimistic springtime Peace of Nicias, the truce marking the end of the first phase of the War; another is 411 bce, after the War has resumed and is going quite badly for Athens, a Fathers and Sons 3 gloomy, violence-torn, pessimistic time.1 Platos contemporaries would knowand many contemporary readers will knowthat Socrates was tried, convicted, and executed in 399 bce for corrupting the youth and introducing false gods. Few contemporary readers, by contrast, will know that Polemarchus, who features prominently in Book I, was executed by the so-called Thirty Tyrants, who, installed by Sparta at the Wars end, ruled briefly and bloodily in 404 bce. Socrates reason for venturing out of Athensto attend a religious festival and offer up my prayers to the goddess (1.327a)is a good example of Platos subtle authorial artistry. As we noted above, the historical Socrates was tried, convicted, and put to death by the citizens of Athens for impiety and corrupting the youth. Plato memorably recounts Socrates defense speech in the Apology (a title that will seem odd, given how unapologetic Socrates is in it, until we realize that apologia is Greek for defense). So Platos depiction of Socrates conventional piety at the very outset of the Republic provides an ironic take on then-recent Athenian history that would not be lost on any of Platos contemporaries. Socrates opening words, I went down, which translate the Greek (katabn), seem an unremarkable way to begin a remarkable book. But we will appreciate their significance and Platos subtle authorial artistry later in the Republic, when, in the famous Allegory of the Cave, Socrates insists that the enlightened philosophers go down again into the cave to govern its benighted prisoners and free those who are capable of making it out. It is the same verb in both cases, and in subtly drawing this parallel Plato seems to be telling us that Socrates interlocutorsand by extension, us, his readers, whatever our accomplishments and pretensiondo indeed live in the darkness of the Cave. Its a strange image you are describing, says Glaucon, and strange prisoners. They are like us, Socrates replies. (7.515a) Socrates tells his unnamed audience that Polemarchus slave tugged on his cloak and asked him to wait. The casual invocation of slavery may bring many contemporary readers up short. Slavery was a fact of life in the Greek world, and lovers of Plato and other great classical authors such as Aeschylus, Aristophanes, and Aristotle, to name just three near the beginning of the alphabet, should at the very least pause 1 Debra Nails, The Dramatic Date of Platos Republic, The Classical Journal, 93.4 (1998), 38396 (p. 385). 4 Platos Republic: An Introduction at the possibility that the cultural achievement of classical Athens was possible only because it was a slave society. Although the claim is not uncontroversial, the consensus of contemporary scholars is that there is slavery in Platos ideal polis. We may have occasion to investigate this later, but for now we might just note the fact that Polemarchus slave is the first person Socrates quotes in the Republic. Although Athenian slavery might partially frame the Republic for modern readers, Plato does not seem to raise it as a background issue worthy of philosophical attention and there is no explicit discussion of its nature or moral status. Plato seems to accept it as something natural (later, he suggests that an individual might be by nature suited to be a slave (4.444b), an idea Aristotle develops in the first book of his Politics) but subject to moral constraintfor example, we are told that Greeks should not enslave other Greeks (5.469c) and that rather than being harsh with his slaves, a good and properly educated person will merely look down on them (8.549a). When Polemarchus finally catches up to Socrates he tells him, You must either prove stronger than we are or you will have to stay here (1.327c). This sounds ominous, but it is just an innocent pun on Socrates name, the central element of which is (cratos), meaning strength or power. One suspects this is not the first time Socrates has endured this rather lame pun, but he replies graciously and without groaning, asking if there is not another alternative, that we persuade you to let us go (1.327c). This little exchange is Platos way of raising an important theme of the Republic: the opposition between force and persuasion, between the irrational and the rational. The conflict sometimes comes to the surface, for example, in the Cave Allegory mentioned above. Education, as Plato conceives of it, involves quite a bit of force: the freed prisoner is compelled to stand up, turn his head [] and look up toward the light (7.515c) and is dragged [] from there by force, up the rough, steep path and then dragged [] into the sunlight (7.515e). Though the enlightened philosophers would rather remain above, they return to the cavenot because they are physically or psychologically compelled to do so, but because they are persuaded to. In response to Socrates appeal to persuasion, Polemarchus jokingly plays a trump card: But could you persuade us, if we wont listen? (1.327e). Here Plato is recognizing a practical limit to the power of Fathers and Sons 5 rational persuasion: people who refuse to listen cannot be persuaded. Most of us have probably encountered people who seem impervious to evidence and argument. More chillingly, the psychologists Brendan Nyhan and Jason Reifler have identified what they call the backfire effect: some of us are psychologically constituted so as to not merely remain unpersuaded by evidence and reasons that should lead us to give up certain beliefs, but actually tend to hold such beliefs even more strongly in the face of such evidenceso attempts to persuade the other by appeals to good evidence are likely to backfire.2 Plato is reminding us that genuine discussion and dialogue, as opposed to dueling monologues, cannot occur when we refuse to entertain reasons and evidence that go against our views. He is raising an important theme that will be at work in the background of the Republic, and raising it in the subtle way skilled literary artists do. There is more we could say about the subtleties of the Republics opening, however the goal was not an exhaustiveand exhausting catalog and discussion of them but rather to help the reader begin to appreciate the literary quality of the Republic and how inseparable its literary and philosophical aspects are for Plato. Cephalus: Justice is Paying Your Debts and Telling the Truth (1.328c331d) The entire conversation that is the Republic takes place at the suburban home of Cephalus, a wealthy merchant, whose son, Polemarchus, has a keen interest in philosophy. Cephalus likes Socrates, and Socrates clearly likes him. Nowadays telling someone that you enjoy talking to them because you enjoy talking with the very old (1.328d) is unlikely to be well received, but Cephalus does not mind, in part because of the association of age and wisdom: since Cephalus is farther along the road of life, he might have some insight about whether that road is rough and difficult or smooth and easy (1.328e). The metaphor of the road or path is one we will see elsewhere in the Republic. 2 Brendan Nyhan and Jason Reifler, When Corrections Fail: The Persistence of Political Misperceptions, Political Behavior, 32 (2010), 30330, https://doi. org/10.1007/s1110901091122 6 Platos Republic: An Introduction Cephalus is a fine spokesperson for moral common sense; his idea of a good life is not a life of sex, drinking parties, [and] feasts (1.329a) but rather one of moderation. Being wealthy does not hurt, he admits, but all by itself material comfort is not sufficient for living well. A good person would not easily bear old age if he were poor, he remarks, but a bad one would not be at peace with himself, even if he were wealthy (1.330a). Despite his conventional decency, Cephalus is not especially reflective and when the discussion turns philosophical, he congenially excuses himself to take care of a religious sacrifice. Cephalus exhibits an attractive kind of humility, as he is sufficiently self-aware to recognize that external factors play an important role in his being morally decent and thus that he himself is not the sole cause of his goodness. Plato is deftly setting up a contrast between character and circumstance, between the inner and the outer, that will come into play later in the Republic as he addresses the question of whether one can cultivate ones soul in such a way that one is more or less impervious to external forces that can lead one to act unjustly. Before Cephalus leaves, Socrates pursues this question of wealth a bit further, asking Cephalus what the greatest good that his wealth has brought him is. Cephalus answer is a bit surprising (and is no doubt part of why Socrates likes him). It is not that it enables a life of selfindulgence, cushy comfort, and lots of toys. Rather, it is that wealth is a kind of buffer against moral temptation: Wealth can do a lot to save us from having to cheat and deceive (1.331b), Cephalus says, and thus it allows a person to face the afterlife without trepidation, since it enables one to live a just and pious life (1.331a). Most of us will agree that wealth is merely instrumentally and not intrinsically valuablethat it is not good in itself, but rather it is good as a means to something else. Cephalus is making a related but subtly different point about the sort of value wealth possesses, that wealth is conditionally good: its goodness depends not just upon the use to which it is put, but on who is doing the puttingon whose wealth it is. If my wealth enables my pursuing pleasures that are ultimately selfdestructive, then my being wealthy is bad for me. A decent and orderly (1.331a) person will benefit from their wealth, since they will use it well. This distinction between conditional and unconditional value provides a nice segue to a distinctively philosophical turn in the conversation. Fathers and Sons 7 Though Cephalus has not himself offered a definition of justice, Socrates hears one lurking beneath the surface and asks, But speaking of this very thing itself, namely, justice, are we to say unconditionally that it is speaking the truth and paying whatever debts one has incurred? Or is doing these things sometimes just, sometimes unjust? (1.331c) It is important to understand that Socrates is not looking for a verbal definition of justice here, the sort of thing that one can look up in a dictionary or use to explain its meaning to someone learning ones language. He is looking for the real definition of justice, for an account of the thing itself. (Here real does not contrast with fake or imaginary but with verbal; etymologically real derives from the Latin word res, which means thing or matter.) There is no question about the verbal definition of dikaiosun, the word we are translating justice: it means morally right conduct generally. But exactly what morally right conduct is is what Socrates wants to know. Trying to get clear about everyday concepts like justice, courage, knowledge, etc., by making explicit what is usually left implicit is one of philosophys main tasks, for Plato. Platos dialogues typically consist of Socrates encountering someone who claims to know the real definition of a virtue like justice or courage or temperance. But after some Socratic question and answer, it becomes clear that the proposed definition will not work, usually because it is inconsistent with other things his interlocutor believes, and that is what happens here. Most of the dialogues end without a definition being arrived atthey end in what scholars call (aporia) difficulty, perplexity. On Cephalus definition of justice (more accurately, the definition Socrates attributes to him) justice is telling the truth and paying ones debts. It is instructive to note what Socrates does not do here. He does not shrug and offer a relativistic platitude such as, well, everyones got a right to their opinion. Socrates does not think that questions like the one he is asking are mere matters of taste, and there would be little point in discussing them if they were. If you think broccoli is delicious and I cannot stand it, an argument about who is right is pointless, since there is no fact of the matter about whether broccoli is delicioushence the maxim de gustibus non est disputandem: there is no disputing about matters of taste. If, by contrast, we disagree about the cube root of 729, at least one of us is wrong. Philosophical questions about the nature of 8 Platos Republic: An Introduction justice (and knowledge, courage, temperance, love, etc.) will seem to many thoughtful people to fall somewhere in between these extremes, not mere matters of taste but not as certain as truths of mathematics. Socrates thinks that there is a correct answer to his question about the nature of justice (and about knowledge, courage, temperance, etc.), so in one sense of the term, he is a realist: he thinks there really is a fact of the matter of what justice is, a way things are that is independent of what we might think, which is the very thing the relativist denies. When Hamlet, by contrast, says that there is nothing either good or bad, but thinking makes it so (Hamlet, II.2.24445), he is expressing an antirealist view about the nature of goodness: things are not mind-independently good or bad; their being good or bad is determined by our attitudes toward them. Realism is not an all-or-nothing affair: one can be a realist about morality, thinking that there really are moral facts such as murder is wrong and kindness is good, but an anti-realist about aesthetics, thinking that beauty really is just in the eye of the beholder. While many readers will be leery about Socrates moral realism, an attractive feature of his method of rigorous cross-examination is that it does not depend on his realism, for it aims to discover whether someones view is consistent with other things they believe. So the elenchus aims to lead the cross-examined party not to the unvarnished moral truth but rather to intellectual self-awarenessand, hopefully, to intellectual humility if, as is often the case, one recognizes that ones beliefs do not hang together consistently. Having noted what Socrates does not do in his conversation with Cephalus, let us look at what he does do. He argues that if Cephalus definition of justice is correct, then it would be just to return a borrowed weapon when its now-deranged owner asks for it back. But Cephalus himself does not think this. Since his definition implies something that he thinks is false, Cephalus should think that his definition is false. This form of argument is as common in everyday life as it is in philosophy. If A implies B and B is false, A must be false too. Any argument that fits this pattern is valid: if its premises are true then its conclusion must be true. If it is true that the sidewalk gets wet if it rains and it is true that the sidewalk is not getting wet, then it must also be true that it is not rainingfor if it were raining, the sidewalk would be getting wet, and it is not; thus, it cannot be raining. If my aggrieved friend says, if (A) Fathers and Sons 9 you were a good friend, then (B) you would have helped me move, I know how the rest of the argument goes even if they do not spell it out: (not-B) you did not help me move; therefore (not-A) you are not a good friend. I might reply by hanging my head in shame and conceding that I am not a good friend. That is, I take the argument to be not only logically valid (in other words, its conclusion must be true if its premises are true) but sound as well: it is valid and its premises are in fact true. But I might also reply by insisting that while the argument is logically valid, it is not sound, since its first premise is false. While it is generally true that a good friend will help one move, it is not true without exception. If I was in the hospital donating a kidney to another friend and was unable to help you move, my not helping does not imply that I am not a good friend. A more plausible version of the first premise would be if (A) you were a good friend and (C) were able to help me move, then (B) you would have done so. On this more nuanced version of the argument, the conclusion to draw from the fact that I did not help is that either (not-A) I am not a good friend or (not-C) I was not able to help. I do not want us to get too bogged down in detail, but attention to the logic of the arguments offered is crucial to doing philosophy in general and to understanding the Republic in particular, especially Book I. Now, just as I had some options in responding to my friends argument, so too does Cephalus have options in responding to Socrates. Perhaps he should concede that his definition is false. But he could also change his mind about whether it would be wrong to return the weapon. This seems less plausible; most of us are surer of particular moral judgments we make than we are about more general moral principles. But if Cephalus is very confident in the truth of his definition, we might be willing to bite the bullet, as philosophers say, and accept an initially unpalatable claim. Another option would be to argue that the definition does not actually imply the problematic judgment, much as I did with my friend in the example above. Or he can challenge Socrates unstated assumption that the definition of justice must be unconditional, never allowing any exceptions. Note that this is not a challenge to Socrates definitional realism; Cephalus can still think that there is a uniquely correct definition while at the same time thinking that the correct definition is the sort of thing that holds only for the most part. In his imposingly titled Groundwork of 10 Platos Republic: An Introduction the Metaphysics of Morals, the great modern philosopher Immanuel Kant insisted that moral principles must hold universally and not merely generally,3 while Platos student Aristotle, by contrast, thought that moral truths hold only for the most part, and that we must not demand more rigor than a subject affords.4 Plato is closer to Kant on this score than he is to Aristotle. We will not settle this dispute here (or anywhere in this book); I raise it not only to show that Cephalus has philosophical options he does not seem to be aware of, but also to show that an important task of philosophy is making the implicit explicit: Socrates assumes that real definitions must hold without exception. While he may be correct about this, he may not be: moral definitions and principles might lack the universality and precision we expect of their mathematical cousins. A related assumption Socrates makes is that there really is one feature that all just things have in common, something in virtue of which they are all just. In other words, there must be an essence of justiceand similarly an essence of courage, wisdom, tree, table, etc. Plato has a surprising view about the nature of these essences, which he calls the Forms: he not only thinks that the Forms are mind-independently real, he thinks that they are more real than the particular things that are instances of them. We will get to that in Chapter Eight, when we will also query the assumption that there is an essencea real definitionof justice and that the task of philosophy is to figure out what that essence is. Polemarchus: Justice is Benefiting Friends and Harming Enemies (1.331d336a) Socrates thinks that the proposed definition of justice has been decisively refuted, but Polemarchus, Cephalus son, disagrees, and for support he appeals to the poet Simonides. This appeal to poetic authority raises an important theme that will be explored later in the Republic: do poets especially great poets such as Homerhave knowledge of things such as the nature of justice? Does the fact that Homer or Pindar or Simonides says something give us a good reason to think that it is true? Anyone who 3 Immanuel Kant, Kant: Groundwork of the Metaphysics of Morals, trans. and ed. by Mary K. Gregor (New York: Cambridge University Press, 1998), p. 34 [Ak. 4:424]. 4 Aristotle, Nicomachean Ethics, I.3 1294b1215. Fathers and Sons 11 has spent much time on Facebook and who has a philosophical bent has probably asked similar questions. Does the fact that George Clooney, for example, thinks drastic action needs to be taken to deal with climate change give me good reason to think so, too? It seems not, but many of us find the deliverances of celebrities persuasive nonetheless. Socrates plainly loves Homer; he quotes him and other poets throughout the Republic. He will reluctantly conclude in Book X that poets and artists generally do not possess the moral authority that the Polemarchuses of the world attribute to them. But for now, he sets this issue aside and queries the definition of justice Polemarchus appeals to. Polemarchus first suggests that justice is giving to each what they are owed. While his fathers definition was too specific, Polemarchus is perhaps too general: what exactly are people owed? Polemarchus answers that we owe good to our friends and bad to our enemies. This is not an outlandish view; indeed, it is commonsense to Polemarchus and his contemporaries. The countervailing Christian idea that we should love our enemies would find few adherents in classical Athens. Socrates makes two arguments against Polemarchus definition of justice as benefiting ones friends and harming ones enemies, but before looking at them, we should attend to a problematic feature of his definition: it divides the moral world into friends and enemiesbut surely that does not exhaust the possibilities. It is likely that most of the people one encounters on any given day do not fall into either category. And though I am lucky enough to have some people I consider genuine friends, my life is not interesting enough for me to have any enemies, alas. A central moral question most thoughtful people ask is what if any moral duties they have toward strangers, especially strangers halfway around the world, who do not fit into either camp. Polemarchus definition of justice gives us no help in answering that question. As with his argument against Cephalus, Socrates argument against Polemarchus account of justice is an indirect argument, aiming to show that the definition implies things that Polemarchus himself thinks are false. Socrates argues that Polemarchus account of justice implies that justice is not especially valuable and moreover that it is a craft of stealing. Since Polemarchus does not think either of those implications is true, Socrates argues, his definition must be false. The pattern is the 12 Platos Republic: An Introduction same one we saw above: A implies B, B is not true, so A must not be true. Here, B has two parts, the sub-claims that justice is not valuable and that justice is a craft of stealing, so the argument is a slightly more complex variation on the argument Socrates made against Polemarchus, but they exhibit essentially the same pattern. P1 If Polemarchus definition of justice is correct, then justice is not valuable and it is a craft of stealing. P2 But it is false that justice is not valuable and that it is a craft of stealing. C Therefore, Polemarchus definition of justice is not correct. As with the argument above, this one is valid: if its premises are true, its conclusionthat Polemarchus definition is mistakenmust be true. Since the argument is valid, the only way to avoid the truth of the conclusion is to find at least one of the premises to be false. Polemarchus feels himself in a bind because he thinks that his definition is true (and thus that the conclusion of Socrates argument is false), and also that both premises seem true. He does not seem to know how to respond: I do not know any more what I did mean, but I still believe that to benefit friends and harm ones enemies is justice (1.334b). Polemarchus plight is not uncommon among Platos characters: they recognize that Socrates has them intellectually cornered but they do not seem to know what to do. Adeimantus describes the experience of many of Socrates interlocutors a bit later in the Republic: Just as inexperienced checkers players are trapped by the experts in the end and cannot make a move, so [your interlocutors] too are trapped in the end and have nothing to say in this different kind of checkers, which is played not with discs but with words (6.487b). I think that Plato puts Polemarchus in this predicament because he wants us, his readers, to engage philosophically in the discussion by doing for ourselves what Polemarchus is not able to do: to carefully scrutinize Socrates reasoning and to think through his assumptions. Perhaps we can help Polemarchus out. Since Socrates argument is valid, the main issue is whether it is sound. Why should we think that its first premise is true? Fathers and Sons 13 Is Justice a Craft? (1.332c334b) Socrates argument that P1 is true (and notice that he offers an argument for a premise that itself is part of a larger argument) turns on the idea of a craft (techn), in Greek, from which words like technique and technology derive. A doctor is a person skilled in the craft of medicine; they know how to use their skill to benefit their friends by healing them and harm their enemies by poisoning them. Similarly, the person skilled in the craft of cooking can use that skill to benefit their friends and harm their enemies via the food they cook. (Readers who have seen the film The Help might think of Minnys special chocolate pie as an example.) The crucial move takes place when Socrates says, Now, what does the craft we call justice give, and to whom or what does it give it? (1.332d) If justice is a craft in the same way that medicine, cooking, navigation, and the like are crafts, then like them it will have its own special sphere in which it operates to benefit friends and harm enemies. Medicines sphere or domain is health; it is there that its skilled practitioner can benefit friends and harm enemies. Medicine is not useful outside its spherefor example, the person skilled in navigation can benefit friends and harm enemies at sea, not the person skilled in medicine. This is not to say that these spheres do not overlap: there is a sense in which a doctor can benefit and harm passengers on a ship, but their being at sea is irrelevant to the doctor benefiting and harming them. Polemarchus does not challenge the assumption that justice is a craft; indeed, he agrees that partnerships are the sphere of the craft of justice. But, Socrates argues, when choosing a partner for checkers we want a skillful checkers player, not someone skilled in the craft of justice. The same can be said for other crafts such as house-building and horse-breeding. When we form a partnership to build a house or buy a horse, we want someone skilled in those crafts, and being just does not make anyone a better builder or breeder. It is when we are not using something and want to safeguard it, Socrates argues, that we choose the person skilled in justice, who will not steal our money or our horse or our prized violin. So, Socrates concludes, justice is not worth very much, since it is only useful for useless things (1.333e). 14 Platos Republic: An Introduction This conclusion is an embarrassing one for Polemarchus view, but it is not fatal to it. The fatal blow comes next. The person most skilled at protecting a computer network, to use an anachronistic example, is the person most skilled at hacking into networks; since they know where the weak spots are, they will know how to patch them. At the end of the film Catch Me If You Can,5 master forger Frank Abagnale goes to work for the FBI, teaching agents how to spot forgeries. Socrates general point is this: Whenever someone is a clever guardian, then, he is also a clever thief (1.334a). But since the person skilled in the craft of justice is the best guardian of an item, they will also be best able to steal it and presumably avoid detection. Thus the just person is a kind of thief, and justice, by being a craft of guarding what is valuable, turns out to be a craft of stealing. Polemarchus is flummoxed. He does not think that justice is useless or a craft of stealing, but he has been led to the view that justice is useless and a craft of stealing by a series of steps that he agreed to. I think that Polemarchus should, but does not, question the assumption driving the argument: that justice is a craft. Certainly, character virtues like justice are similar to crafts in interesting and important ways. For example, both are practical, involving know-how. Both are acquired by practice, by doing. Both are desirable to possess and objects of praise. But the (or at least a) crucial difference between them is that crafts are morally neutral, while character virtuesmoral virtuesare not. As Socrates points out, the doctor, who possesses the craft of medicine, can use their craft for good or ill, to benefit and harm. If Polemarchus definition of justice is correct, the doctor uses their craft to benefit their friends and harm their enemies and thereby exhibits justice. But a doctor who uses the craft of medicine to harm their friends is acting unjustly, on Polemarchus view. Whether the doctor acts justly depends upon how they use their craft. Crafts are goodbut they are conditionally good, good only if used appropriately; their moral goodness is not intrinsic. Virtues, by contrast, seem to be unconditionally, intrinsically good. Possessing them makes their possessor morally better off, even if it makes them, say, financially worse off. (Courage might seem to pose a problem for this claim, but 5 Catch Me If You Can, dir. by Stephen Spielberg (DreamWorks Pictures, 2002). Fathers and Sons 15 we can set that worry aside for now.) When Socrates asks, Is someone a good and useful partner in a game of checkers because he is just or because he is a checkers player? (1.333a), he is treating the craft and the virtue as the same kind of thing. Instead of agreeing, Polemarchus should say, That is a false dilemma, Socrates. You are assuming that someone cannot be both just and a good checkers playerbecause you are assuming that justice is a craft, and it is not. I want to play against someone who is good at checkersthe challenge makes the game more funand someone who is not going to cheat. Being just does not make anyone a better builder or breeder or checkers player, but it does make someone a better partner to engage in those crafts with, since it makes her less likely to take unfair advantage or cheat. Perhaps Polemarchus has some implicit grasp of this point, which may be one reason why he remains unconvinced by Socrates argument against his definition. It turns out that the first premise of Socrates argument against Polemarchus definition is more complex than it initially seemed. It is not P1 If (A) Polemarchus definition of justice is correct, then (C) justice is not valuable and (D) justice is a craft of stealing but rather P1* If (A) Polemarchus definition of justice is correct and (B) justice is a craft, then (C) justice is not valuable and (D) justice is a craft of stealing. With the structure of P1 thus clarified, Polemarchus has a good response to Socrates. His conceding that C and D are both false no longer entails that A is false (i.e., that his definition of justice is not correct). Instead, the falsity of C and D entail that either A is false or B is false (and maybe both). And we have independent reasons for thinking B is false: character virtues such as justice are like crafts in many ways, but they are not crafts, since crafts are morally neutral while character virtues (and vices) are morally loaded. 16 Platos Republic: An Introduction Speaking of Friends (1.334c335a) The next argument has the same structure as the first: the definition implies something that is false, so it must be falseor at least Polemarchus ought to think it is false. In fact, Socrates seems to show that Polemarchus definition implies that it is just to harm people who have done us no injusticei.e., who are not our enemies: Then, according to your account, it is just to do bad things to those who do no injustice (1.334d). Here the culprit is Polemarchus mistaken account of who a friend is. Socrates distinguishes between subjective and objective accounts of friendship. On a subjective view, you are my friend if I think you are good and useful; what matters are my beliefs about you. On the objective view, you are my friend if in fact you are good and useful, regardless of whether I think so. Polemarchus opts for the first, subjective option, but Socrates points out that we are often mistaken about this sort of thing, which can lead to harming our friends and benefitting our enemies. Notice that here Polemarchus recognizes that his view is defective, since it implies something he knows to be false. My account ( [logos]) must be a bad one (1.334d), he says, proposing that they modify the subjective account of friendship, opting for a hybrid account that combines the objective and subjective accounts: Someone who is both believed to be useful and is useful is a friend; someone who is believed to be useful but is not, is believed to be a friend but is not (1.334e). This exchange shows Polemarchus in a better light than the first. He is much more active than in the first argument, where for the most part he limited himself to one-word replies to Socrates somewhat leading questions. At the conclusion of the first argument he seemed helplessly befuddled, vaguely recognizing that there was some problem with his view but sticking to it nonetheless: I do not know any more what I did mean, but I still believe that to benefit ones friends and harm ones enemies is justice (1.334b). In this exchange he not only clearly recognizes the problem (his subjective account of friendship) but articulates the solution: let us change our definition (1.334e) of friendship. He is more rationally engaged in this exchange and provides a pretty good model for thinking philosophicallywhich, in the end, really just comes down to thinking clearly. It may be that his rational Fathers and Sons 17 vision is sharper in this exchange, however I suspect it is not that his vision has improved, but rather that the problem is more visible in this exchange than in the first. But Does the Just Person Harm Anyone? (1.335b336a) Where Socrates first criticisms of Polemarchus definition are indirect, aiming to show that it implies things that Polemarchus himself rejects, the last criticism is more direct, challenging the definition itselfand, indeed, is a direct challenge to an element of Greek commonsense morality that would seem to most Athenians to be unassailable. The proposed definition cannot be right, Socrates argues, because it is never just to harm anyone (1.335e). It is an argument that is important both to the scheme of Book I of the Republic and to moral philosophy generally. One of the arguments key elements is the concept of a virtue, which we employed without exploring whether a virtue such as justice is a craft. While we are perhaps likelier to think of virtue in the singular, referring to someones character in general (or, anachronistically, to sexual chastity), it is usually plural in the Republic. Indeed, in Book IV we will find Socrates giving accounts of the four cardinal virtues: justice, moderation, courage, and wisdom. The Greek word is (aret), which does not have the necessarily moral connotation that the English word virtue possesses. The word virtuoso retains this nonmoral sense; it is still an evaluative term, but not a morally evaluative one. The word good often functions this way. When you call someone a good person, you are morally evaluating and praising them; when you call them a good dancer or a good mechanic or a good thief, you are evaluating them, but you are not evaluating them morally; you are saying that they are good at a particular craft or activity. Some translators try to remind their readers of this non-moral aspect by opting for excellence instead of virtue in translating aret. This makes sense, since if things like dogs and knives have virtueswhich they do, as Plato understands the conceptit must have a non-moral dimension. But our translator opts for virtue, so to avoid confusion we will follow his lead. The concept of a virtue is best understood in terms of the concept of a function. A things function is the work it does, its goal-directed purpose. The Greek word for function is (ergon), which is the root of the 18 Platos Republic: An Introduction English word ergonomic. Some readers have ergonomic computer keyboards that are wedge-shaped or chairs that are ergonomically designed, which means that they are designed to enable their users to work more efficiently as they carry out the objects function. More technically, the function is the goal-directed activity characteristic of the kind of thing in question. Artifacts like knives and cars have functions, but so too do natural objects. The function of a knife is to cut; the function of a heart is to pump blood. In one sense, a things function is what makes it what it is. Understood in terms of function, a plastic knife and a metal knife have more in common with each other than a plastic knife and a plastic fork do. Understood materially rather than functionallythat is, understood in terms of the matter they are composed of rather than their tasksthe plastic knife and plastic fork are more similar to each other than either is to the metal knife. A hallmark of modern science since Galileo and Newton is jettisoning functional or teleological (that is, goal-directed) explanations of natural phenomena in favor of material and mechanistic explanations. Rain does not have a purpose in the modern worldview; that rain waters crops and thus enables life is a welcome side-effect of rain. A scientific account of why it rained this morning will appeal to various meteorological facts, not to the function or purpose of rain. But these functional or teleological explanations, while out of place in physics and chemistry, still find a home in biology and psychology, for example, and in ordinary life. When in The Silence of the Lambs Clarice seeks Hannibals help in catching Buffalo Bill, he encourages her to think teleologically: What does he do, this man you seek? When she answers, He kills women, Hannibal replies in his eerie, sing-song voice, No! That is incidental. He is telling her that until she understands the goal around which he organizes his murderous activityi.e., until she understands Bills functionshe will not be able to understand him, much less to catch him.6 A virtue, then, is the state that enables the thing to perform its function well, and a vice, by contrast, is the state that prevents the thing from performing its function well. Sharpness is the virtue of a knife, since sharpness is what enables the knife to cut well, and dullness is a knifes vice, since it prevents the knife from cutting well. A dull knife still might cut, but it will not cut 6 The Silence of the Lambs, dir. by Jonathan Demme (Orion Pictures, 1991). Fathers and Sons 19 well. So a virtue is a good-making feature of thing: sharpness makes for a good knife, since a sharp knife cuts well. If it sounds odd to talk of a knifes virtue, keep in mind that excellence is another way to translate aret. The virtue of a heart is a bit more complicated, which makes sense, given how complicated hearts are, but the basic idea is the same: the hearts virtue is the condition that enables it to pump blood well. Now that we have explored the concept of a virtue, let us see how Socrates puts it to work in his third, direct argument against Polemarchus definition of justice. Since possessing the relevant virtue makes something good, you make something worse by depriving it of its virtue. Thus, making a knife duller makes it worse. Now of course there may be times when a dull knife is preferable to a sharp one: one does not use a sharp knife as a prop in a movie or play, because it is too dangerous. But notice how the knifes function has quietly changed: as a prop, its function is not to cut but to appear to do so. You do not give scalpel-sharp scissors to a kindergartener but instead scissors that do not cut as well, since we will sacrifice cutting capacity in favor of safety. The upshot of all this is that to harm something is to make it worse off with respect to the relevant virtue. The key move in the argument occurs when Polemarchus agrees with Socrates suggestion that justice is the human virtue (1.335c). There is no mention of the human function heresomething that Platos student Aristotle will make the centerpiece of his ethicsbut we can reason backwards to it, if we are so inclined. Perhaps our function is, at least in part, to live peacefully in communities; if so, then justice will be the trait, or surely among the traits, that will enable us to do so. When speaking of making objects worse, we tend to reserve harm for animate objects and employ damage for inanimate ones. It sounds odd to say that I harmed the lawnmower by not putting oil in the engine. But harm and damage are both ways to make something worse, and in both cases I make the thing worse by depriving it of the relevant virtue. So, just as I would damage the knife by depriving it of its characteristic virtue, sharpness, I would harm a person by depriving them of the characteristic human virtue, justice: people who are harmed must become more unjust (1.335c). But, Socrates asks, how could a just person, acting justly, make someone else less just? A musician cannot by exhibiting musical 20 Platos Republic: An Introduction excellence make others less musical, he thinks, any more than an excellent parent or teacher can make someone else a worse parent or teacher through the very exercise of their excellence. The very idea is incoherent, Socrates thinks. Thus the proposed definition is intrinsically, rather than extrinsically, flawed: the problem is not that the definition has false or undesirable implications; the problem is that its core idea, that justice involves harming those who deserve it, makes no sense. This conclusion has fascinating implications for theories of punishmentthough this is not something that Socrates pursues here. If Socrates is correct, then retributivist accounts of punishment are deeply morally mistaken. Only punishment aiming at the wrongdoers moral improvement would be justified; retributive punishments, which seek to inflict harm because the wrongdoer deserves to suffer, would not be justifiable. Here it is important to remember that not all pain is harmful; we often inflict pain on ourselves and others for our and their own goodand it is especially heart-rending when that other is a small child or companion animal with whom we cannot communicate our reasons for inflicting pain. We will see in the next chapter that Thrasymachus, who bursts on the scene at this arguments conclusion, has a lot to say in opposition to this arguments key premise, that justice is the human virtue, so we will not explore the argument in great detail here. One might wonder, though, about Socrates point that a person or thing possessing virtue V cannot, by exercising V, make other things un-V or less V. Sharp knives become dull by their repeated use, after allthough the great Daoist Zhuangzi (aka Chuang Tzu) might attribute this to a lack of excellence in the person wielding the knife, since Cook Dings knife finds the empty spaces between the joints and thus is still as sharp as if it had just come off the whetstone, even after nineteen years.7 But let us set this aside and attend to how differently Polemarchus reacts to this Socratic refutation. After the first argument, he still stuck to his definition, insisting that justice was benefiting friends and harming enemies, even though he sensed something was amiss. Here, by contrast, he is completely convinced that his definition is mistaken, and profoundly so. 7 Zhuangzi: The Complete Writings, trans. by Brook Ziporyn (Indianapolis: Hackett Publishing, 2020), p. 30. Fathers and Sons 21 Moreover, he agrees to be Socrates partner in battle (1.335e) against those who advocate it. It is worth noting, as we wind down this chapter, how Socrates seeks to preserve the moral authority of the poet Simonides, to whose definition Polemarchus appealed when entering the conversation. When Polemarchus first jumps into the argument, Socrates describes Simonides as a wise and godlike man (1.333e)though perhaps a bit ironically. A few pages later, having, he thinks, decisively refuted the definition, he suggests that the definition could not be Simonides after all, since no wise and godlike person could be so mistaken about the nature of justice. Instead, it must be the definition of a wealthy and powerful person seeking to cloak their bad conduct in the mantle of justice. This is yet another of the subtle ways in which Plato works important themes into the argument. As noted above, whether poets have the moral authority customarily ascribed to them will be explored later in the Republic. We have covered a lot of ground in this chapter. Hopefully readers have a good grasp of some of the key concepts that will be explored in the remainder of the Republic and especially of the give-and-take that characterizes philosophical conversation. Some Suggestions for Further Reading Kenneth Dover, Greek Popular Morality in the Time of Plato and Aristotle (Indianapolis: Hackett Publishing, 1994), is a rich source for the shared morality of the day. Gregory Vlastos, Socrates Rejection of Retaliation, in Socrates: Ironist and Moral Philosopher (Ithaca: Cornell University Press, 1991), pp. 17999, investigates the radical nature of Socrates separating justice and retaliation. Vlastos was one of the preeminent Plato scholars of the twentieth century. Interested readers with a fondness for Greek tragedy will want to see Mary Blundell, Helping Friends and Harming Enemies: A Study in Sophocles and Greek Ethics (New York: Cambridge University Press, 1991). 22 Platos Republic: An Introduction M.I. Finley, Ancient Slavery, Modern Ideology (New York: Penguin Books, 1983) is a classic historical study of slavery both ancient and modern. A revised version, edited by Brent Shaw, which includes a long essay by Shaw on the responses to Finleys arguments, was published by Markus Weiner Publishers in 2017. Zhuangzi: The Essential Writings, trans. by Brook Ziporyn (Indianapolis: Hackett Publishing, 2009), will interest readers intrigued by the story of Cook Ding. It and the Dao De Jing, which appears in several translations, are foundational texts of philosophical Daoism and present a stark contrast with Platos intellectualism and rationalism. Readers interested in the historical persons depicted in the Republic and the other dialogues will find Debra Nails, The People of Plato (Indianapolis: Hackett Publishing, 2002) a fascinating and valuable resource. Greek vase, ca. 550 BCE. Photograph by Materia Viva (2010), Wikimedia, CC BY-SA 4.0, https://commons.wikimedia.org/wiki/ Category:Mus%C3%A9e_Saint-Raymond,_26172#/media/File:MSR26172-MV-R-b.jpg 2. Taming the Beast: Socrates versus Thrasymachus, Book I The last half of Book I (336a354c) depicts Socrates encounter with Thrasymachus. Like most characters in the Republic, Thrasymachus is a real person, and the views Plato attributes to him square with what is known of the historical Thrasymachus. Thrasymachus is a sophista professional, itinerant teacher of rhetoric, or the art of persuasion. Platos worry about sophists is that their teaching is neither grounded in nor aimed at the truth; its only concern is persuasion. Enter Thrasymachus: Justice Is Whatever Benefits the Powerful (1.336a39b) Thrasymachus bursts into the conversation like a wild beast, and Socrates twice remarks how frightening it was. His entrance might be merely an overly aggressive case of calling bullshit were it not for the antipathy he clearly has for Socrates. Socrates asks questions but never answers them, Thrasymachus complainsand not, Thrasymachus thinks, because of any Socratic wisdom of knowing that he does not know the answers, but because of his love of honor (1.336c): Thrasymachus thinks that Socrates just wants to win arguments. He responds to Socrates assertions of the value of justice as a thing more valuable than even a large quantity of gold (1.336e) and of intellectual humility (we are incapable of finding it (1.336e)) with a loud, Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.02 26 Platos Republic: An Introduction sarcastic laugh, dismissing them as just Socrates usual irony (1.337a). This last charge might sound strange to modern ears; irony is often prized for its elegance. But here, irony ( [eirneia]) is seen as false modesty and thus a vice. In his Nicomachean Ethics Aristotle rates ironywhich he calls mock modestyas one of the vices flanking the virtue of truthfulness (roughly: being a straight shooter), the other being boastfulness,1 and in his Rhetoric he notes that people often respond to irony with anger, since it can seem to show contempt.2 Perhaps that is what earns Thrasymachus ire. In any case, Thrasymachus has an answer to Socrates question about the nature of justice, one he is very proud of: justice is nothing other than the advantage of the stronger (1.338c). Two things to notice straightaway about Thrasymachus account are its political nature and its reductive, deflationary tone. By the stronger he means the politically powerful, who make laws to benefit themselves; good people follow those rules, thinking it just to do so, which benefits the rule-makers. The definitions deflationary, reductive aspect is brought out in the nothing other than locution. Claims that love is nothing but a biochemical phenomenon or a fairy tale or a social construction are meant to deflate the kinds of lofty claims one encounters at wedding receptions and on Valentines Day cards. Thrasymachus offers his definition of justice in a similar vein. Though Socrates and Thrasymachus agree that justice is beneficial, they disagree about whom it benefits. Socrates thinks that justice, like any character virtue, benefits its possessor: my being just makes my life better. Thrasymachus, who will soon deny that justice is a virtue at all, claims that my being just benefits someone elsenamely, the politically powerful rule-makers, who benefit from my following the rules which they have crafted for their own benefit. A just person, Thrasymachus argues, always gets less than an unjust one (1.343d): they do not cheat their business partners or customers, they do not cheat on their taxes, and when they govern they make laws that benefit others rather than themselves. We will see soon enough that Socrates rejects Thrasymachus picture of what a happy or flourishing human life looks like. Thrasymachus is a materialistnot in the philosophical sense of thinking that there are no 1 Aristotle, Nicomachean Ethics, IV.7 1127b2231. 2 Aristotle, Rhetoric, II.2 1379b3031. Taming the Beast 27 immaterial objects, but in the everyday sense of thinking that material success is the main goal of life and measure of success. Thrasymachus is also an egoist: ones own interests are the ultimate standard for how one should act. Note that the egoist does not counsel doing whatever one feels like doing at any moment, for that may not be in ones interest. Acting impulsively is often at odds with enlightened self-interest, so it is not something Thrasymachus endorses. And there may be times when following the rules will be to ones advantage, especially if one is likely to be caught and punished for breaking the rules. While it is almost always in ones interest to appear to be justa point that Glaucon and Adeimantus will focus on in Book IIit is rarely in ones interest to actually be just, Thrasymachus thinks. On his view, people who wish to be just are either nave simpletons who cluelessly enable their own exploitation, or they are savvy enough to recognize their own inability to act unjustly with impunity and so agree to the rules in order to protect themselves against those strong enough to do so. Justice is for the weak, he thinks: Those who reproach injustice do so because they are afraid not of doing it but of suffering it (1.344c). Five Arguments Against Thrasymachus Definition of Justice There is more to say about Thrasymachus definition of justice, but the best way to do that is to turn to the arguments Socrates gives against it. As with the conversations with Cephalus and Polemarchus, Socrates will argue from premises that Thrasymachus accepts to conclusions that are at odds with those premises. That is, he will try to show that Thrasymachus view is at odds with itself, and thus that Thrasymachus himself has reason to discard or at least revise his view. Socrates makes five such arguments. The first two target Thrasymachus answer to the Republics first question about the nature of justicethat is, his claim that justice is whatever benefits the stronger. The last three target his answer to the Republics second question about whether a just life is happier than an unjust one. We will take them each in turn. 28 Platos Republic: An Introduction The Error Argument (1.338c343a) I have dubbed the first argument the error argument because it turns on the possibility that rulers, being fallible, are prone to error in crafting laws. The argument is straightforward. Thrasymachus agrees that justice is or at least requires following laws laid down by the rulers. But rulers, being fallible, sometimes make mistakes and thus enact laws that are not in their own interests. Sosometimes, at leastjustice is not what benefits the stronger. Since on Socrates view an adequate definition of a things essence must not allow for exceptions, Thrasymachus definition must be rejected or revised, since there are times when justice does not benefit the stronger. Reconstructed in premise-conclusion form, Socrates Error Argument against Thrasymachus goes like this: P1 In a political system, the rulers are stronger than the ruled. (1.339a) P2 Justice is (obedience to) whatever the rulers command. (1.339c) P3 Rulers sometimes err and do not command what is to their advantage. (1.339d) C So, justice is not (always) the advantage of the stronger. (1.339d) The argument seems deductively valid; that is, its conclusion must be true if its premises are true. Since Thrasymachus rejects the conclusion, rational consistency requires him to reject at least one of the premises. Hopefully this requirement makes sense. Since the argument is valid, if all its premises are true, its conclusion would have to be true. So if I think the conclusion of a valid argument is false, I cannot think that all the premises are in fact true, because if the premises were in fact true, the conclusion would be true, too. It is irrational to think that all the premises of a valid argument are in fact true and to think that the conclusion that follows from them is false. If I think the conclusion of a valid argument is false, I must also think at least one of the premises is false. Someone who does not value consistency will be unmoved by all of this. We have probably all encountered a kind of skepticismand perhaps embodied it with youthful exuberancethat is skeptical about Taming the Beast 29 consistency itself. What is so great about consistency?, such a skeptic asks. Who cares if I am being inconsistent? If the skeptic is bookish, they might even quote from Ralph Waldo Emersons well-known essay, Self-Reliance: A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines.3 Or they might appeal to F. Scott Fitzgeralds assertion in The Crack-Up that the test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function.4 One way to respond to our skeptic is to point out that for Emerson the bogeyman wasnt consistency but rather foolish consistency: With consistency a great soul has simply nothing to do [] Speak what you think now in hard words, and to-morrow speak what to-morrow thinks in hard words again, though it contradict every thing you said to-day.5 It is refusing to change ones mind that Emerson is attacking here. And Fitzgerald is not questioning the value of consistency or celebrating inconsistency; he is concerned less with belief than he is with action: One should, for example, be able to see that things are hopeless and yet be determined to make them otherwise.6 There is nobility in fighting the good fight, he suggests, even when we do not believe we will succeed. Ultimately, though, if the skeptic continues to deny the value of consistency, there is little one can say to convince them otherwise, since rational argument depends upon consistency. Such a person is in effect demanding a sound argument for why they should find sound arguments persuasive. It they stick to their guns, there is no point in arguing with them. To do falls afoul of the folksy wisdom of a needlepoint pillow I happened upon years ago: Never try to teach a pig to sing; it wastes your time and annoys the pig. Thrasymachus, whatever his other faults, is not this sort of skeptic. He is skeptical about the value of justicewe will soon see that he thinks it is a vice rather than a virtuebut he is not skeptical about the importance of consistency. Let us assume that Thrasymachus recognizes the argument as logically valid. (Since it wasnt until Aristotle that 3 Ralph Waldo Emerson, Essays (New York: Harper Perennial, 1995), p. 41. 4 F. Scott Fitzgerald, The Crack-Up (New York: New Directions Publishing, 2009), p. 69. 5 Emerson, p. 41. 6 Fitzgerald, p. 69. 30 Platos Republic: An Introduction anyone worked out the notion of logical validity, it is anachronistic to speak of Thrasymachus as recognizing the arguments validity, but doing so seems a harmless aid to clarity.) If he wants to resist its conclusionwhich presumably he does, since it says that his account of justice is falsehe must think at least one of the premises is false. P1 seems unassailable: at least insofar as strength is understood in terms of political power, the law-making rulers are stronger than their subjects. P2 is never challenged by Thrasymachus or anyone else, despite Socrates bringing it up almost half a dozen times. I cannot help but think that these are winks or gentle nudges to prod readers to look more closely at P2. Thrasymachus agrees that it is just to obey the rulers (1.339b), a proposition that he repeatedly assents to: it is just for their subjects to do whatever their rulers order (1.339d); it is just for the others to obey the orders they give (1.339e); it is just to obey the orders of the rulers (1.340a). While obeying the law is typically just, we might ask whether it is always, unconditionally, just to do so, just as Socrates questioned Cephalus definition. Many readers will think that there is a presumption in favor of obeying the laws of our communities: obedience is the default position. But fewer will think that this presumption is exceptionless, for there seem to be times when this presumption does not holdfor example, if a law is unjust. Some thinkers, among them Thomas Aquinas and Martin Luther King, go even farther and think that unjust laws are not really laws at all but are counterfeits, and that we should no more obey them than we should accept a $20 bill we know to be counterfeit. P2, as I have stated it, does not merely claim that legal obedience is just; it claims that that is what justice is. It is a subtle but important difference, apparently unnoticed but accepted by Thrasymachus. When Socrates asks him, And whatever laws they make must be obeyed by their subjects, and this is justice (( ) [to dikaion]: the just)?, he replies Of course (1.339c). By adding the definite article the in Englishthe adjective, just, gets promoted to a noun, the just, which is a typically Platonic way to talk about justice itself. On this view, all there really is to justice is obeying the rules, regardless of their content. Justice on such a view is merely a matter of convention: there are no mindor culture-independent facts about whether something is really just or not. The only fact that makes something just is that it is a rule of ones Taming the Beast 31 community. If the laws of ones community mandate racial segregation, then justice requires obedience to them. Some readersthough fewer now than sixty years agowill agree with this, holding that one should always obey the law, even laws one considers unjust, though one can work within the system to change unjust laws. Notice, too, that the conventionalism about justice expressed in P2 implies that there really is no standard by which to assess the laws of ones community as just or unjust. All there is to justice on such views is following whatever rules there are, regardless of their content, and there is no way to assess that content morally. Different communities have different rules, but if this deep cultural conventionalism or relativism is correct, no communitys rules are better than any others, they are just differentand the same goes within a community over time: if a community allows slavery at time t1 but abolishes it at t2, the new legal code is not better, it is just different. This is something that few people are willing to accept, upon reflection. When we associate conventionalism and relativism with open-mindedness and tolerance of other cultures practices and norms, they can seem attractive, but they often seem significantly less so when we examine their implications. To draw on some vocabulary developed in the previous chapter, this conventionalism about justice is an anti-realist view: there are no culture-independent moral facts by which to morally assess the laws and norms of ones culture. The contrast between nature and convention between what is mind- and culture-independent and what is mind- and culture-dependentis a pervasive theme in the Republic. The border between Illinois and Wisconsin seems purely conventional, the result of a decision to draw the line in a particular place. The border between Wisconsin and Minnesota seems more natural, since the Mississippi and St. Croix rivers are natural objects, existing whether we think they do or not. But even this boundary is not completely natural, since it is the border only because people decided it was. We have spent a lot of time on a view no one in the Republic mentions because I think Plato wants us, his readers, to do what his characters do not do, to think through issues that are ignored or given short shrift in the text. If we pause and double-click here, so to speak, examining the issues more thoroughly than Socrates interlocutors do, we will be doing philosophy for ourselves. And if we do, we might well think that P2 is 32 Platos Republic: An Introduction false or at least in need of serious revision, even if no one in the Republic questions it. Despite Socrates repeated prompting, Thrasymachus ignores P2. He will reject P3, which he initially assented to but now, on reflection, finds problematic. But before Thrasymachus addresses P3, Cleitophon tries to come to his rescue, suggesting that Thrasymachus view is that justice is what the stronger believe to be to their advantage. In short, Cleitophon is suggesting that the Error Argument is irrelevant, since it misunderstands Thrasymachus view. Polemarchus objects that is not what Thrasymachus said. It is telling how Socrates responds here: If Thrasymachus wants to put it that way now, let us accept it (1.340c). This suggests that, contrary to what Thrasymachus says about him, Socrates is not primarily interested in winning an argument; he is interested in getting at the truth. If Cleitophons revision more accurately reflects what Thrasymachus thinks, then that is what we should attend to, Socrates thinks. What he meant is more important than what he said, for Socrates. To think otherwise would be a foolish consistency indeed. Thrasymachus declines to go through the door Cleitophon has opened for him, however. Instead, he does what philosophers often do: he makes a distinction between different senses of a key term or concept. Here, Thrasymachus distinguishes between the ordinary and precise senses ruler, claiming that P3 is true in the ordinary sense of ruler but false in the precise, philosophical sense. Thus he can consistently reject the arguments conclusion, since he thinks that P3, the seemingly plausible claim that rulers sometimes err and make laws that are not to their own advantage, is false, strictly speaking. In the strict or precise sense, rulers do not make mistakes, he claims. Do you think Id call someone who is in error stronger at the very moment he errs? (1.340c), Thrasymachus asks. For all his bluster and swagger, Thrasymachus shows himself capable of subtle, philosophical thought when he distinguishes between the precise and ordinary senses of terms. When someone makes an error in the treatment of patients, Thrasymachus asks rhetorically, do you call him a doctor in regard to that very error? (1.340d) The same goes for accountants, grammarians, and any person said to possess a craft. A craftsperson, after all, possesses expertise and knowledge; the names for possessors of such expertisecarpenter, shepherd, doctor, Taming the Beast 33 teacher, etc.are not merely descriptive but are to an extent normative, indicating that their possessor has earned the right to be so called. Someone might be on the roster as quarterback or employed by the university as a teacher. But if they are so bad at their jobs, we might want to withhold the name: Hes no quarterback, says the disgruntled football fan of a now-departed player. The fan is not saying that, say, Jay Cutler did not play that position; they would be likelier to say he is not a quarterback if the description is factually incorrect, if say the player were a linebacker and not a quarterback. Typically, s/he is no x, where x is a term for a craftsperson, makes the normative claim that the person in question is not good enough at their craft to merit the title. It is a normative issue, rather than a descriptive one, and it extends beyond names for craftspeople, as when someone says of rapor rock and roll or jazz, in their early daysthats not music. This issue, by the way, is an important one in Confucianism. Confucius and especially his follower Xunzi were concerned with the rectification of names (zhengming), given the importance of social roles to their thinking. Someone who regularly fails to display the required filial piety does not deserve to be called a sonor, as Thrasymachus would put it, is not a son in the precise sense. So Thrasymachus thinks that while P3 of the Error Argument is true in the ordinary, descriptive sense of ruler, it is false in the precise, normative senseand that is the relevant sense here. There is a certain logic to his view. Since a craftsperson is so called because they possess the requisite knowledge, when they make a mistake, they seem to lack this knowledgeor at least they are unable to act on it at that moment. It is when his knowledge fails him that he makes an error, Thrasymachus says, and in regard to that error he is no craftsman. No craftsman, expert, or ruler makes an error at the moment when he is ruling, even though everyone will say that a physician or a ruler makes errors (1.340e). When he agreed with P3 earlier (1.339c), he had the ordinary, imprecise sense in mind. But on the precise accountand Socrates is a stickler for precise accounts (1.340e)P3 is false, since no craftsman ever errs. There is certainly something to what Thrasymachus says. But is he overstating his case in holding that any error renders the craft-title in question inapplicable? Does expertise really require such infallibility? 34 Platos Republic: An Introduction A baseball player need not throw a perfect game in to be called pitcher in the precise sense. If Thrasymachus were right, there have only been twenty-three genuine pitchers in the history of major league baseball. It is not just that perfect games depend on more than the pitchers skill. And it is not just a matter of human imperfection. Rather, it seems that some level of failure is consistent with possessing the relevant expertise, which is rarely an all-or-nothing matter. The best hitters in baseball, after all, make outs more often than they get hits. What level of imperfection is acceptable varies by craft: a batter who gets a hit only a third of the time is an excellent hitter; an orthopedic surgeon who successfully sets a broken bone for only a third of their cases seems far from competent. Thrasymachus distinction between the precise and ordinary senses of ruler allows him to avoid accepting the conclusion that his definition of justice is false, since it allows him to claim, with some reason, that one of the arguments premises is false. Socrates does not challenge Thrasymachus distinction between the ordinary and precise senses of ruler (and, presumably, of other terms for experts in various crafts). Instead, he turns the distinction back against Thrasymachus in what we will call the Craft Argument. The Craft Argument (1.341c348b) The heart of the Craft Argument is Socrates insistence that craftspeople, in the strict sense, always seek to benefit their subjects, never themselves. Doctors, for example, insofar as they are doctors, seek to heal their patients; horse-breeders seek to raise healthy horses; etc. If we think of craft-knowledge as a kind of strengthas cognitive-practical strength rather than physical strengththen the expertise the craftsperson possesses is a kind of strength; thus crafts rule over and are stronger than the things of which they are the craft (1.342c). Stated in premiseconclusion form, the Craft Argument begins thus: P1 All crafts seek to benefit the objects over which they rule, not their practitioners. P2 All objects over which a craft rules are weaker than the craft, which is stronger. C1 So, all crafts seek to benefit the weaker, not the stronger. Taming the Beast 35 The argument is valid, and though Socrates has given only a few examples in support of P1, Thrasymachus accepts it. So far, so good. Now, to get to his desired conclusion that Thrasymachus account of justice is false, Socrates has to assume that justice is a craft; there is no way to get to a conclusion about justice without a premise about justice. Since Socrates needs to make this assumption, let us state it clearly in the second half of the Craft Argument: P3 Justice is a craft. C2 Therefore, justice seeks to benefit the weaker, not the stronger. C3 Therefore, justice is not the advantage of the stronger. This half of the argument is valid, too. C2 follows from C1 and P3 by plugging justice into the general claim that all crafts seek to benefit the weaker. And then C3 follows from C2, because if justice seeks to benefit the weaker, then justice is not the advantage of the stronger. Thrasymachus initial reaction to the conclusion is a lesson in how not to react rationally to an argument: Tell me, Socrates do you still have a wet nurse? [] Because she is letting you run around with a snotty nose, and does not wipe it when she needs to! (1.343a). Needless to say, such insult-ridden responses, sadly not uncommon in cyberspace, do not pass philosophical muster. And Thrasymachus second response is not much better. For rather than challenging one of Socrates premises, as one should do when one rejects the conclusion of a valid argument, Thrasymachus does what many of us often do: he simply repeats his view, loudly and more stridently: justice is really the good of another, the advantage of the stronger ruler, and harmful to the one who obeys and serves (1.343b). His merely repeating his view rather than engaging with Socrates objections to it echoes Polemarchus reminder in the opening scene that one cannot be persuaded to change ones mind if one will not listen. Thrasymachus responding as he does is not terribly surprising when we remember his profession: he is a sophist, a wandering teacher of rhetoric, who teaches students how to make speeches in law courts. If he is any good at his job, he can teach his students to make a speech for or against any view. You want to argue that the defendant is guilty? 36 Platos Republic: An Introduction Heres how you do that. You want to argument that the defendant is innocent? Heres how you do that. You want to figure out whether the defendant is really guilty or not? Not my department. He is a master of the art of disputation, engaging in what Plato calls eristic, the etymology of which is telling: Eris was the Greek goddess of strife; but for her rolling an apple engraved to the fairest at a divine wedding reception, the Trojan War might not have happened. To be (eristikos) is to be fond of strife, to enjoy combatat least the verbal variety. However effective good speeches are at persuading ones listeners of pre-determined conclusions, they are not especially effective for arriving at philosophical conclusions. Socrates thinks his method of elenchus, the method of question-and-answer that proceeds from premises his interlocutor agrees to, is a better way to get at the truth. Now if you already knowor, like Thrasymachus, think you know the truth about an issue, a rhetorically sound speech (or op-ed piece or book) may be the best way to bring your audience around to your view. But if, like Socrates, you do not think you know the answer to the question, Socratic cross-examination seems a better way to get at the truth, whatever it will turn out to be. Whatever direction the argument blows us, Socrates says a bit later in the Republic, that is where we must go (3.394d). Where Thrasymachus draws on his rhetorical skills to get to that pre-determined end, Socrates will accept the [answer] that seems right to me after I have investigated the matter (1.337c). This difference between their approaches is ultimately the difference between indoctrination and inquiry. It is a shame that Thrasymachus is unwilling or unable to query Socrates argument, for it is not as airtight as Socrates seems to think it is. As is often the case in the Republic, we will have to do for one of the interlocutors what they cannot or will not do for themselves. For starters, Thrasymachus might question P1, the claim that all crafts seek to benefit their objects, not their practitioners. The trouble here is not that the argument Socrates gave in support of P1 is too brief, although it is that. From just a few examples of crafts that aim at the benefit of their objects rather than their practitioners, Socrates arrives at a general conclusion that all crafts are like this. Perhaps more examples would strengthen this inductive argument. Taming the Beast 37 A more serious problem with the Craft Argument is that Socrates himself provides a counterexample to its first premise when he introduces the craft of wage-earning (1.346c). Crafts are distinguished by their different ends and their different means for achieving their endsthat is, by their different functions: every craft differ[s] from every other in having a different function (1.346a). The function of a doctor, in the precise sense, is healing patients, not making money. And similarly for the other crafts Socrates lists: navigation, horse-breeding, etc. Making money is the function of a different craft, the craft of wageearning or money-making. If doctors and horse-breeders and shipcaptains and teachers benefit financially from practicing their crafts, it is because they possess another craft, the craft of wage-earning. Many readers will be familiar with chefs and carpenters and doctors who are truly expert at their crafts but who lack business sense. At the other end of the spectrum are those famous for being famous celebrities whose only discernible skill is money-making, an ability to monetize their otherwise-devoid-of-accomplishment existences. By now the point is probably obvious: the craft of money-making is practiced for the benefit of the practitioner. While medicine and teaching are other-focused, wage-earning is self-focused: it benefits the craftsperson. And it is true that you might practice this craft altruistically, as when you want to earn more money so you can better provide for your family or community, but the craft itself aims to benefit the craftsperson. So right off the bat, Thrasymachus has grounds to resist the conclusion that his definition is false. Of course, the conclusion of an unsound argument might still be true. Just as there is nothing inconsistent about a juror thinking the defendant actually committed the crime in question but voting to acquit because the state did not prove its case beyond a reasonable doubt, there is nothing inconsistent in believing that the conclusion of an unsound or invalid argument is true. If Thrasymachus were more fair-minded, he might concede that his definition of justice might be false but insist that Socrates has not shown that it is. Another and perhaps better option for Thrasymachus is to cast doubt on P3, the claim that justice is a craft. As noted above, this is an implicit assumption of the argument, not an explicit claimthough Socrates did assert it earlier, in arguing against Polemarchus: what does the craft we call justice give, and to whom or what does it give it? (1.332d) This 38 Platos Republic: An Introduction would be a good move for Thrasymachus to make, since we already have good reason to think that P3 is false: while crafts and character virtues are similar in many ways, crafts are morally neutral whereas character virtues are not. If justice is not a craft, then the general claim that crafts are other-focused would not apply to it. Now it looks like the argument is doubly unsound, since we have good reason to doubt both P1 and P3, so Thrasymachus is not rationally compelled to accept its conclusion. Socrates might reply that even if justice is not a craft, ruling is. But then the Craft Arguments conclusion needs to be changed as well, which stymies Socrates attempt to make progress toward understanding what justice is by showing what it is not. The argument so modified would not be a refutation of Thrasymachus definition of justice but rather of the view that rulers, in the precise sense, seek not their own benefit but rather the benefit of those they rule. We might think this is true, at least of good rulers, but Thrasymachus could here raise the problems with P1, reminding Socrates that his own example of wage-earning is a counterexample to the general claim that crafts are not practiced primarily for the benefit of the craftsperson. Why not think ruling is analogous to wage-earning, Thrasymachus could ask, and aims at the benefit of the ruler? At the very least, Socrates has not given him compelling reasons to think that it is not. An important lesson here is how interlinked the arguments of the Republic are. Earlier I suggested that the important conclusion to draw from Socrates attempted refutation of Polemarchus was not the one he explicitly drew but rather that justice and other moral virtues are not crafts. Whether this was the lesson Plato hoped wed learn is beside the point, at least to the extent that one goal in reading the Republic is to do philosophy ourselves, to engage in imaginary dialogue with Socrates as we try to get at or at least close to the truth of the matter. If the assumption that justice is a craft is false, its reappearing as a premise here undermines the Craft Argument. The Outdoing Argument (1.348b350d) Even if the Craft Argument is unsound, it explicitly raises the Republics second main question of whether the just life is happier than the unjust life. This questions urgency leads Socrates to leap-frog the more Taming the Beast 39 theoretical question of the nature of justice in favor of the practical question of which whole way of life would make living most worthwhile for each of us (1.344e). Modern moral philosophy often focuses on particular actions, especially choices in dilemmas. Sometimes the dilemmas are intentionally artificial, to bring out larger moral principles lurking in the background. Many readers will be familiar with the trolley problem and its numerous variations: is it permissible to divert a runaway trolley car onto a track where it will kill one worker if doing so will save five people working on the track the trolley is on? Other times, the dilemmas are more the stuff of everyday life: is aborting a pre-viability fetus permissible or not? Socrates question is far more general than these, as it concerns whole ways of life rather than particular actions. It concerns not so much what we ought to do as the way we ought to live (1.352d). Socrates approach focuses on persons rather than actions and takes the unit of evaluation to be lives rather than choices and actions. This approach, known as Virtue Ethics, has enjoyed a resurgence among moral philosophers in recent years, and though virtue ethicists often look to Aristotle for inspiration, we see its roots in the ethical thought of Plato and Socrates. This virtue-centric concern comes to the fore almost immediately in the third of Socrates arguments against Thrasymachus, the Outdoing Argument, to which we now turn. Since Socrates has shifted his attention from the first to the second of the Republics main questions, his aim now is not to refute Thrasymachus definition of justice but rather Thrasymachus claim that complete injustice is more profitable than complete justice (1.348c). The question of whether a just life is happier than an unjust one has great practical implications, given the overwhelmingly plausible assumption that each of us wants to be happy. Few of us would dispute that the just life is morally better than the unjust life; the issue here is whether the just life is prudentially betterwhether, as we put it in the Introduction, having a good life requires leading a good life. Thrasymachus thinks not, since a just man always gets less than an unjust one (1.343d). If Thrasymachus is right about which life is happier, then each of us has a strong reason to act unjustly: if a just or morally good life is always at odds with happiness, living a just life will inevitably frustrate a core desire each of us has. Socrates argues that, despite its apparent plausibility, Thrasymachus 40 Platos Republic: An Introduction view is profoundly mistaken, since morality and happiness are not fundamentally at odds with each other. Far from being an impediment to happiness, a just life is at least a necessary condition of a happy life, on Socrates view, since we cannot be happy unless we are just. Thrasymachus understands happiness in terms of material success, in terms of power and its trappings. On his view, the more a person gets, the happier they will be. Life is a competition between people striving to outdo each other where the winner is the person who is able to bend others to their will. Few people, I trust, try to inculcate Thrasymachus materialism and egoism in their children. Socrates last words, nearly, to the jury that found him guilty of impiety and sentenced him to death, are a request for a favor: When my sons grow up, gentlemen, if you think they are putting money or anything else before goodness, take your revenge by plaguing them as I have plagued you; and if they fancy themselves for no reason, you must scold them as I scolded you, for neglecting the important things and thinking they are good for something when they are good for nothing. If you do this, I shall have had justice at your hands, both I myself and my children.7 Despite his profound disagreement with Thrasymachus materialistic conception of human flourishing, Socrates does not argue directly against it but instead, in a pattern that by now is familiar, he tries to show Thrasymachus that a key premise he believes inhere, that the unjust person outdoes everyone else (1.344a)does not support and in fact is at odds with the conclusion Thrasymachus holds. This notion of outdoing is central to the Outdoing Argument. The Greek word is (pleonexia); etymologically it is a combination of pleon (more) and echein (to have). Thrasymachus unjust person wants to have more than anyone else and recognizes no legitimate moral constraints on his pursuit of his goal. Fans of classic cinema will find a fine example of pleonexia in John Hustons 1948 film, Key Largo, starring Humphrey Bogart, Lauren Bacall, and Edward G. Robinson. In a confrontation between Frank McCloud (Bogart) and Johnny Rocco 7 Plato: Five Dialogues: Euthyphro, Apology, Crito, Meno, Phaedo, trans. by G. M. A. Grube (Indianapolis: Hackett Publishing, 1981), p. 44 (41e42a). Taming the Beast 41 (Robinson), McCloud tells captive innkeeper James Temple (Lionel Barrymore), that he knows what Rocco wants: McCloud: Rocco: Temple: McCloud: Rocco: McCloud: Rocco: McCloud: He wants more, dont you, Rocco? Yeah. Thats it. More. Thats right! I want more! Will you ever get enough? Will you, Rocco? Well, I never have. No, I guess I wont. You, do you know what you want? Yes, I had hopes once, but I gave them up. Hopes for what? A world in which there is no place for Johnny Rocco.8 Roccos insatiable desire for more is the heart of pleonexia. It is almost as though the object of this desire is secondary: whatever people want, the pleonectic person wants more of it, wants to outdo everyone else. The rest of us, not strong enough to bend others to our wills to get what we want, live in fear of the Johnny Roccos of the world, those amoral creatures who are strong enough to bend us to their will to get what they want. Glaucon, playing devils advocate, will soon articulate the Thrasymachan view that justice is a deal the weak make to protect themselves against the caprice of the stronger. Those who reproach injustice, Thrasymachus says, do so not because they are afraid of doing it but of suffering it (1.344c). If enough of us weak folk band together and gain political power, we can make laws that protect us against the Thrasymachuses and Roccos of the world. After all, that is all justice is, in the conventionalist view Thrasymachus articulated at the outset: the rules the politically powerful make to serve their own interests. We should note, though, that Thrasymachus shifts gears at the outset of the Outdoing Argument and articulates a view that does not square with his conventionalism. For he counts injustice not as a vice but as a virtue: Socrates: Do you call one of the two a virtue and the other a vice? 8 Key Largo, dir. by John Huston, prod. by Jerry Wald (Warner Bros., 1948). 42 Platos Republic: An Introduction Thrasymachus: Socrates: Thrasymachus: Socrates: Thrasymachus: Of course. That is to say, you call justice a virtue and injustice a vice? That is hardly likely, since I say that injustice is profitable and justice is not Do you really include injustice with virtue and wisdom, and justice with their opposites? I certainly do. (1.348ce) Thrasymachus is here articulating immoralism, the view that what most people think of as the wrong way to act is actually the right way: what are conventionally thought to be character vices are actually virtues. Unlike the conventionalism Thrasymachus expressed earlier, immoralism is a realist view: there are mind-independent moral facts that provide standards by which to evaluate a societys conventions and norms. Athenian culture takes justice to be a virtue and injustice to be a vice. Here, Thrasymachus is saying that Athenian culture get this backwards, since injustice is really the virtue and justice the vice. Thrasymachus immoralism makes sense when we pair the last chapters discussion of what a virtue is with his materialistic conception of human flourishing. A virtue is the condition that enables a thing to perform its function well. So a knifes virtue is sharpness, since that is what enables the knife to cut well. If our function is to outdo others, to get more stuff, then of course injustice is a virtue and justice is a vice, since injustice enables and justice prevents our getting more than others: a just man always gets less than an unjust one (1.343d). Socrates notices the challenge posed by Thrasymachus shift to immoralism: it is not easy to know what to say (1.348e) in light of Thrasymachus jettisoning the moral order that would usually serve as the background of a conversation like this. But he cannot simply presuppose the usual background without begging the questionthat is, without assuming the truth of what he is trying to proveagainst Thrasymachus: he needs to argue against Thrasymachus immoralism, not just assume it is wrong and that the traditional moral order, on which justice is a virtue and injustice a vice, is correct. Socrates direct target in the Outdoing Argument is Thrasymachus immoralist view that justice is the vice and injustice is the virtue; if he can show this, he will knock Taming the Beast 43 out the support for Thrasymachus view that the unjust life is happier than the just life. Thrasymachus thinks that an unjust person tries to outdo everyone and if they are sufficiently good at being bad, they will succeed. He thinks that the just person, by contrast, is a simpleton, easily duped by the more crafty and complicated unjust person. Socrates gets Thrasymachus to agree that the just person seeks to outdo only unjust people, but Thrasymachus is skeptical that the person will succeed at this, being so polite and innocent (1.349b). Socrates once again appeals to the analogy between crafts and virtues: a craftsperson, he argues, tries to outperform the person lacking the craft in question, while the craftlacking person tries to outdo everyone. Thrasymachus agrees to this, and also to Socrates claim that a craftsperson is wise and good, which makes sense at least with respect to the craft in question. A skilled carpenter possesses a kind of technical wisdom, knowing how to build a wrap-around deck or a roll-top desk, for example. The person who lacks the craft, by contrast, is ignorant and bad: they lack the craftspersons knowledge and are not, for example, a good carpenterthey are not properly called a carpenter at all, if Thrasymachus earlier point about the precise sense of craft-terms is correct. The craftsperson, Socrates thinks, wants to perform the craft in question better than someone who lacks it, not someone who possesses it: they want to outdo those unlike them, not those like them. The craft-lacking person, by contrast, wants to outperform everyone, both those like them and those unlike them. Similarly, the just person wants to outdo unjust people, those unlike them, while the unjust person wants to outdo everyone, both those like and those unlike them. If all of this is correct, the just person resembles the craftsperson, since each wants to outdo only those unlike them, the unjust and craftlacking person, while the unjust person resembles the craft-lacking person, wanting to outdo everyone, both those unlike them and those like them. Since each of them has the qualities of the people he is like (1.349d) and Thrasymachus has agreed that the craftsperson is good and wise, while the craft-lacking person is neither, it follows that the just person is good and wise while the unjust person is neither; from there it is a short trip to the conclusion that justice is virtue and wisdom and that injustice is vice and ignorance (1.350d). 44 Platos Republic: An Introduction Since most of us, I assume, are not immoralists, we will agree with Socrates conclusion. But as often is the case in Book I, Socrates argument for his conclusion is problematic. The first problem is that the argument relies on the analogy between crafts and virtues, a troublesome analogy that bedevils much of Book I. Given the difference between character virtues and craftsthe latter are morally neutral while the former are notwhy should Thrasymachus accept the claim that each has the qualities of the one he resembles (1.350c)? After all, the kinds of knowledge the just and skilled persons require are very different. In possessing a skill, the craftsperson possesses a morally neutral knowledge of how to do certain things. As Socrates noted in his argument with Polemarchus, the craftsperson can use their skills for good or ill: a doctor can use their medical expertise to heal or kill. Even someone who possesses a skill that seems intrinsically bad imagine, say, an assassincan use that skill for good ends as well as bad: assassinating Hitler seems a good thing. The lesson here is that arguments from analogy rise and fall on the presence of relevant similarities and dissimilarities, respectively, between the things being compared. Given the important dissimilarity between crafts and virtues, Thrasymachus would be right to push back on this premise. Another problem with the Outdoing Argument, which many readers will have already noticed, is that its very first premise, the claim that the skilled person seeks to outdo only the unskilled person rather than another skilled person, seems to be not merely false but obviously false. Socrates is probably correct that when it comes to tuning the lyre, the lyre-player wants to do better than a non-musician. Where there is one correct way to do something, genuine experts will do that thing in the same way. But when it comes to playing the lyre, for example, rather than merely tuning it, a skilled musician does not merely want to play better than a non-musicianthat is not much of an achievementthey want to outperform another lyre-player. Readers might be puzzled by Socrates confident assertion that a doctor [] when prescribing food and drink [] want[s] to outdo a nondoctor (1.350a), given how competitive doctors can be. Some doctors are better diagnosticians than others, some cellists are better at playing Bach than others, some philosophers are better at interpreting Plato than others, some investors are better at spotting under-valued companies than others, etc. Developing these Taming the Beast 45 skills is often fueled at least in part by competition and a desire to outperformto outdo, as Socrates puts itother experts: the desire to be the best at x-ing, whatever x may be. So even setting aside the disanalogy between crafts and virtues, the Outdoing Argument flounders because its key premise is false or at least highly questionable; at the very least, it needs more defense than it gets. Even if we agree with Socrates that Thrasymachus immoralism is mistaken, we can see that the Outdoing Argument is far from conclusive against it. Perhaps a lesson here is that being too personally invested in ones views, as Thrasymachus seems to be, can get in the way of adequately defending them. If I see your argument as refuting me rather than refuting a view I hold, as attacking me as a person rather than a premise or principle I subscribe to, I may well react as Thrasymachus does. Earlier he responded to the Error Argument with a literally snotty put-down of Socrates; here he is tamer in defeat, blushing and producing a quantity of sweat that was a wonder to behold (1.350d). But clearly a more dispassionate attitude would serve him better. After all, if the goal is to discover the truth about justice, seeing that ones view was mistaken is actually something to welcome, since by clearing away false views we get closer to the truth. Such an attitude is a tall order for most of us, but even if we think it is not fully achievable, given human nature, it does present an ideal to which we can aspire. The Common Purpose Argument (1.350d352d) There is a discernible change in Thrasymachus demeanor after the Outdoing Argument, one noted by Glaucon towards the beginning of Book II: I think that Thrasymachus gave up before he had to, charmed by you as if he were a snake (2.358b). Thrasymachus thinks his immoralism, a view he regarded as bold and daring, has been refuted, and since speech-making has been ruled out, he announces that he will just agree with Socrates from here on. In again urging Thrasymachus not to answer contrary to his own opinion (1.350c), Socrates reminds us of the nature of Socratic cross-examination, which is personal in the sense of its aiming to help the person being questioned to discover the truth by examining how well their views hang together or if they hang 46 Platos Republic: An Introduction together at all. Especially when the topic is an important one like justice, being in error can have disastrous consequences. In the conclusion of Book I of his Treatise of Human Nature David Hume famously said, Generally speaking, the errors in religion are dangerous; those in philosophy only ridiculous.9 Socrates could not disagree more, since so much hangs on the philosophical question of whether the just life is happier than the unjust life. (Hume, in response, would think that philosophical questions have far less effect on how we live our lives than Socrates thinks; far from being able to govern our conduct, reason is and ought only to be the slave of the passions, and can never pretend to any office than to serve and obey them.10) If Thrasymachus is mistaken that the unjust life is a happier life, this mistake is not merely theoretical or conceptual or abstractly philosophical, for the argument concerns no ordinary topic but the way we ought to live (1.352d); it is a mistake that will have profound implications for the quality of ones life. If Socrates is right about justice, then Thrasymachus view is a prescription for a life of glittering misery. So it is a shame that Thrasymachus gives up, for the final two arguments of Book I deserve more scrutiny than they get. The first of these is the Common Purpose Argument, which aims to refute Thrasymachus claim that injustice is stronger and more powerful than justice (1.351a). This claim is implied by the immoralist view that Socrates tried to refute with the Outdoing Argument. Thrasymachus thinks that injustice empowers its possessor to outdo everyone, to take control of and rule a city-state. Socrates argues that Thrasymachus has woefully misidentified injustices power: injustice has the power, first, to make whatever it arises inwhether it is a city, a family, an army or anything elseincapable of achieving anything as a unit, because of the civil wars and differences it creates, and, second, it makes that unit an enemy to itself (1.351e). Socrates idea is that even a criminal gang cannot successfully achieve its goals unless some kind of justice regulates the gangsters dealings with each other. Spelled out in premise-conclusion form, the Common Purpose Argument goes something like this: 9 David Hume, A Treatise on Human Nature, ed. by L. A. Selby-Bigge, 2nd ed., rev. by P. H. Nidditch (Oxford: Clarendon Press, 1987), p. 272 [Book I, Part iv, Section 7]. 10 Hume, Treatise, p. 415 [II.iii.3]. Taming the Beast P1 If x enables successful common action and y prevents this, then x is stronger than y. P2 Justice enables and injustice prevents successful common action. C Therefore, justice is stronger than injustice. 47 The argument is logically validits conclusion must be true if its premises are trueand its premises seem in fact true, so it is sound, to boot. As the preceding arguments have all been problematic, this success almost seems worth celebrating. But before Socrates and company start with the ancient Athenian equivalent of high-fiving, they would do well to pause and note that even if the argument is sound, the conclusion it establishes seems too weak, for it shows that justice is merely instrumentally good, useful for any group to achieve its goals, be they just or unjust. Socrates thinks that justice (and especially a reputation for possessing it) is instrumentally good, but presumably he wants to show that justice is also intrinsically goodthat its goodness is internal and not dependent merely on the external benefits it brings about, that all by itself it makes its possessor better off. If justice helps a criminal enterprise be more unjust, then it is hard to see how it is a moral virtue; instead, it seems to be just another skill or craft and merely conditionally good: it is good when aimed at good ends and bad when aimed at bad ends. So even though the Common Purpose Argument is sound, it does not seem to prove what it ought to prove. It is a shame that Thrasymachus wounded pride prevents him from challenging the Common Purpose Argument. If he had, Socrates might have given it up, or perhaps on reflection he might have regrouped and responded that the argument shows at least that Thrasymachus immoralism is incorrect. After all, Thrasymachus thinks injustice is a virtue and justice is a vice because the former enables and the latter prevents its possessor from achieving happiness: immoralism implies that injustice is stronger than justice. So in showing that the opposite is true, that justice is stronger than injustice, Socrates shows that immoralism is false. So even if the Common Purpose Argument comes to the wrong conclusion about the nature of justice, it still packs a punch against Thrasymachus immoralism. 48 Platos Republic: An Introduction The Function Argument (1.352d354c) The last argument in Book I reprises and repurposes some concepts employed earlier in Book I and discussed in the last chapter, especially the nature of a virtue. Socrates seems to regard it as a knock-down argument that the just life is happier than the unjust life, but we will see that even he is ultimately dissatisfied with it. The ideas of virtue and function came up earlier in Book I, in one of Socrates arguments against Polemarchus view that justice is helping friends and harming enemies. A things function is its goal-directed purpose, the activity characteristic of things of its kind. So a knifes function is cutting, a hearts function is pumping blood, etc. Socrates define[s] the function of a horse or anything else as that which one can do only with it or best with it (1.352e). So even though one can cut with a spoon or a fingernail, cutting is a knifes function since a knife cuts best. A virtue, we have seen, is what enables a thing to perform its function well: anything that has a function performs it well by means of its own peculiar virtue and badly by means of its vice (1.353c). Thus a knifes virtue is sharpness, because sharpness enables a knife to cut well. Since we make knives and other tools to perform certain tasks, it is easy to see an artifacts function and virtue. But natural objects like hearts, eyes, and kidneys, have functions, too. And indeed, in the Function Argument, Socrates is concerned about the function and virtue of the soul ( [psuch], whence the word psyche (the upsilon is often transliterated as a y, so psuch becomes psyche, for example)). Though Socrates will later argue that the soul is immortal, it is best not to read any religious beliefs into soul here. Instead, think of a soul as a life-force. All living things have souls on this view. Indeed, Aristotle will distinguish between vegetative souls, which enable metabolic processes, sentient souls, which enable feeling and locomotion, and rational souls, which enable thought. Humans, he thinks, have all three, and non-human animals have the first two. Thus Socrates asks, What of living? Is not that a function of a soul? (1.353d) He then claims, and Thrasymachus half-heartedly agrees, that justice is a souls virtue and injustice its vice (1.353e). He made this claim earlier, in the argument Taming the Beast 49 with Polemarchus: But is not justice human virtue? (1.335c). Just as a sharp knife cuts well, a just soul lives well. And what is happiness but living well? Thus Socrates concludes that a just person is happy, and an unjust one is wretched (1.354a). Spelled out in premise-conclusion form, the Function Argument looks like this: P1 A things virtue enables its function to be performed well. (1.353c) P2 Living is a function of the soul. (1.353d) P3 Justice is a souls virtue, injustice a vice. (1.353e) C1 So, the just person lives well; the unjust person lives poorly. (1.353e) P4 Happiness is living well; unhappiness is living poorly. (1.354a) C2 So, the just person is happy; the unjust person is unhappy. (1.354a) The argument is logically well constructed: if its premises are true its conclusions must be true. But even if we agree with Socrates that its premises are true, we might wish that Thrasymachus would push back a bit, for it is not clear that we are justified in thinking them true. P1 is unproblematic: it is just a definition of what a virtue or excellence is. But we might worry that P2 is weaker than it needs to be: living needs to be the function of the soul, not merely a function of the soul, for the argument to work. While one cannot be justor unjust, for that matterif one is not alive, it is hard to see how mere biological life is the issue here. A deeper worry is P3, which Thrasymachus is already on record as rejecting: on his immoralist view, injustice is the virtue and justice the vice. While we might agree that Socrates was right to reject Thrasymachus immoralism, if we are fair-minded we should concede that his argument for doing so leaves much to be desired, relying on both a false equivalence between skills and virtues and on the false premise that the skilled person seeks to outdo only the unskilled person. The Common Purpose Argument gives an indirect reason for thinking P3 is true and thus that Thrasymachus immoralism is false, but it is overly dependent on the bad analogy between skills and virtues. What Thrasymachus should do, but does not do, is to push back and argue that Socrates may well be correct that the just life is happier, but the Function Argument does not prove it, since two of its key premises may 50 Platos Republic: An Introduction well be false and at the very least Socrates has not given us reasons for thinking they are true. Book I would be very different if Thrasymachus gave Socrates more of a run for his money. Socrates himself is dissatisfied at the end of Book I, and he seems to implicitly acknowledge that his argumentsespecially the last onerely on premises that Thrasymachus finds doubtful and that even sympathetic but fair-minded readers wish were better supported. Moreover, Socrates recognizes a flaw in his procedure: he started to address the Republics second question of which life is happier before answering the first question on the nature of justice. It is a moment of typical Socratic insight: the result of the discussion, as far as I am concerned, is that I know nothing, for when I do not know what justice is, I will hardly know whether it is a kind of virtue or not, or whether a person who has it is happy or unhappy (1.354c). So Socrates himself realizes that he is not really justified in asserting the Function Arguments key premise, P3. It is not that he thinks it is false; he has not gone over to Thrasymachan immoralism. But he recognizes that he has not given the immoralist a good reason to change their mind, and he has not given himself a good reason to believe what he believes. Several years ago, Donald Rumsfelds talk of the known unknown was held up to some ridicule or at least befuddlement in the popular media. But one need not approve of Rumsfelds role in the Second Gulf War to appreciate the essentially Socratic nature of the point he was making. There are things that we know, and we know that we know them: our names, where we live, etc. And there are things that many of us do not knowwhat the capital of Belarus is, Ted Williams lifetime batting average, how to play the celloand we probably know that we do not know them. But it is those things that we do not even know that we do not know that can be a source of trouble, as any student who discovers, during an exam, that they now know that they do not know something... Had they come to this higher-order awareness before the exam, they could have asked their professor or a classmate for help. As is so often the case in other areas of life, timing is everything in moving from not knowing that we do not know something to knowing that we do not know it. Taming the Beast 51 Coming to this kind of higher-order knowledge is often an epiphany; it certainly was for Socrates when he realized that his wisdom consisted in his not thinking he knew what he did not knowin his knowing what he did not know (Apology 20d21e). And the same goes at the end of Book I, when he realizes that he does not yet know what justice is, and thus that the arguments he is given that the just life is happier rely on premises he is really not entitled to assert. He is displaying a kind of intellectual humility that is sadly in short supply in our age (as it was in his). Even if his interlocutors have not challenged him when they could have and should have, Socrates does not let himself get away with thinking he knows something he does not know. While Book I ends on a down-note, we will see in the next chapter that there is reason yet for optimism. Some Suggestions for Further Reading For an excellent discussion of the notion of virtue, interested readers should see Heather Battaly, Virtue (Malden, MA: Polity Press, 2015). Readers interested in Confucius views on the strict senses of terms will find them in Book 13, chapter 3 of his Analects. The Analects of Confucius: A Philosophical Translation, trans. by Roger Ames and Henry Rosemont (New York: Ballantine Books, 1998) is excellent and includes a very helpful introduction. The later Confucian Xunzi (aka Hsun Tzu) explores the issue in greater depth in chapter 22 of the text that bears his name. Interested readers should see Xunzi: The Complete Text, trans. by Eric Hutton (Princeton: Princeton University Press, 2014), https://doi. org/10.2307/j.ctt6wq19b Readers interested in the historical Thrasymachus will find fragments of his work in The Greek Sophists, ed. by J. Dillon and T. Gergel (New York: Penguin Books, 2003). There are many discussions of Socrates encounter with Thrasymachus. An excellent one to start with is Roslyn Weiss, Wise Guys and Smart Alecks in Republic 1 and 2, in The Cambridge Companion to Platos Republic, ed. by G. Ferrari (New York: Cambridge University Press, 2007), pp. 90115, https://doi.org/10.1017/ccol0521839637.004 52 Platos Republic: An Introduction Readers interested in relativism might start with chapters two and three of James Rachels and Stuart Rachels, The Elements of Moral Philosophy, 8th ed. (New York: McGraw-Hill, 2014). Thomas Aquinas, Treatise on Law, trans. by Richard J. Regan (Indianapolis: Hackett Publishing, 2000), is the locus classicus for the view that unjust laws are not really laws; interested readers will also want to see Martin Luther King Jr., Letter from Birmingham Jail, in Why We Cant Wait (New York: Signet Classics, 2000), pp. 7695, for a modern application of that view. Readers interested in a scholarly treatment of Socrates method might start with Gregory Vlastos, The Socratic elenchusMethod Is All, in Vlastos, Socratic Studies, ed. by Myles Burnyeat (New York: Cambridge University Press, 1994), pp. 129. For readers intrigued by the concept of irony, there is no better place to begin than the first chapter of Gregory Vlastos, Socrates, Ironist and Moral Philosopher (Ithaca: Cornell University Press, 1991), pp. 2144. Franz Caucig, Socrates with a Disciple and Diotima (1810). Photograph by Sporti (2014), Wikimedia, Public Domain, https://commons. wikimedia.org/wiki/File:Franc_Kav%C4%8Di%C4%8D_-_ Sokrat_z_u%C4%8Dencem_in_Diotimo.jpg#/media/File:Franc_ Kavi_-_Sokrat_z_uencem_in_Diotimo.jpg 3. A Fresh Start: Book II Socrates is not the only one who is dissatisfied with the resultsthe non-results, reallyof Book I. Glaucon and Adeimantus feel let down, too. It is not that they have been convinced by Thrasymachus. Quite the contrary. They agree with Socrates that the just life is happier than the unjust life, but they do not find Socrates arguments persuasive and thus they recognize that they cannot defend or justify that belief, to themselves or others. We could put their predicament thus: they believe that the just life is happier, but they do not know that it isand they know that they do not know this. When thinking about knowledgemore precisely, about propositional or factual knowledge, the kind of knowledge involved in knowing that certain claims are true, in contrast to the knowing how to do certain things, the sort of knowledge that is distinctive of the skills and crafts discussed in earlier chaptersa good place to start is to think of knowledge as a matter of justified true belief. On the JTB conception of knowledge, so-called because it defines knowledge as Justified True Belief, I know that the White Sox won the 2005 World Series because I believe that they won, my belief that they did is justified (since it is based on good reasons: I watched (and re-watched) the deciding game, I have confirmed their victory on various reliable websites, etc.), and that belief is true. We all have various beliefs that are true but unjustified and beliefs that are false but justified. For example, looking at the usually reliable and accurate clock on my office wall, I form the belief that it is half-past eight and thus that I still have time for some last-minute preparation and Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.03 56 Platos Republic: An Introduction perhaps another coffee before my nine oclock class. But unbeknownst to me the clock is malfunctioning because of a power surge, and it is actually a quarter past nine (and most of my students have given up on me). Even though my belief is false, it seems justified, since my evidence is a clock that has always been reliable. More on point, though, are cases in which my belief is true but unjustified. Suppose that I know that my clock is wildly inconsistent, speeding up and slowing down with no rhyme or reason. Even so, I come to believe that it is eight oclock after glancing at the clock. Even if it is eight oclock, I am inclined to think that I do not know that it is eight oclock, because my belief, while true, is not justified: it is based on evidence I myself regard as unreliable. Similarly, suppose I just have a feeling that the White Sox will win today, and suppose further that my gut-feelings about the outcomes of baseball games are not especially reliable, being wrong at least as often as they are right. Even if the Sox win, you would be right to disagree when I say, I knew they would win today!, since a crucial element in knowledge, namely justification, is missing. Even though the JTB conception of knowledge does not feature in the Republic, it has its roots in another of Platos dialogues, the Theaetetus, where Socrates and Theaetetus consider (among other things) whether it is true judgment with an account ( [logos]) that is knowledge (201d).1 They ultimately reject the JTB account because, ironically, they cannot come up with a satisfactory account of what an account or reason is. We will see in Chapter Eight that Socrates has a very different conception of knowledge in the Republic. But even though the JTB conception of knowledge lacks Platonic bona fides (not to mention contemporary philosophical disagreements about what justifies beliefs and indeed about whether knowledge is best thought of as JTB), it is helpful in understanding the dynamics of Books II and III. Glaucon and Adeimantus, having been raised properly, have (let us assume) a true belief about the relation between justice and happiness. But they recognize that they lack a justification for this true belief, and they hope Socrates can help provide them with one. We saw in the previous chapter that Socrates arguments in support of this belief leave a great deal to be 1 As before, 201d refers to the page in the standard edition of Platos works. Translations of the Theaetetus are from Plato: Theaetetus, trans. by M. J. Levett, rev. by Myles Burnyeat, ed. by Bernard Williams (Indianapolis: Hackett Publishing, 1992). A Fresh Start 57 desired, a fact of which Socrates as well as Glaucon and Adeimantus are painfully aware. Thrasymachus, for his part, would insist that Glaucon and Adeimantus do not know that the just life is happier, not because they lack a justification for their true belief, but because their belief is false: the just life is not happier than the unjust life, on his view. The most striking feature of their request for help is their asking Socrates not to proceed as he did in Book I and give us [yet another] theoretical argument that justice is stronger than injustice (2.367b). Nor are they asking Socrates to become more like Thrasymachus and give long speeches. But they also do not want him to crank out argument after argument, as he did in Book I. They are reasonably bright young men, but they are not philosophically sophisticated, and want something that is convincing without being too abstract. Glaucons approach in seeking a justification for his belief that the just life is happier is twofold. First, he makes a distinction between three different kinds of goods, which will help them clarify the kind of good Socrates should show justice to be. Second, he articulates three claims or theses that he thinks capture the heart of Thrasymachus position, adopting the role of devils advocate. It is not, Glaucon assures Socrates, that he believes any of these Thrasymachan claims (2.358c, 2.361e). But if Socrates can show him how to refute these theses, Glaucons belief that the just life is happier will inch closer to being justified. Three Kinds of Goods (2.357a358a) There is healthy scholarly disagreement about the details of Glaucons division of goods, but we can get a good sense of the division without getting tripped up in a scholarly tangle. For the sake of clarity, I will depart slightly from Glaucons ordering, switching the second and third categories. The first kind of good comprises intrinsic goods, which we welcome not because we desire what comes from it, but [] for its own sakejoy, for example, and all the harmless pleasures that have no results beyond the joy of having them (2.357b). The idea is that we value certain things, experiences, and activities in and for themselves and not for their consequences. This way of putting it is not quite right, though. Possessing these goods makes our lives go better, and having ones life go better 58 Platos Republic: An Introduction because one possesses x seems to be a consequence of possessing x. We can get clearer about what Glaucon means if we think of the relation between such goods and a good life as a part-whole relation, rather than a means-end relation. Enjoying a sunset is not a means to having a good life, it is part of a good life. To modify an example from the philosopher John Akrill (which he made in a different but related context), driving to a golf course is a means to playing a round of golf that is external to the game: I drive to the course in order to play a round. I drive the ball off the tee and putt in order to play a round of golf, but these activities are not external means to playing golf, as driving to the course is; they are constituent elements or internal parts of playing a round of golf. So Glaucons intrinsic goods are constituent parts or elements of a good life conceived as a whole; they are not external, instrumental means to such a life. Where first category goods are best thought of in terms of the partwhole relation, the second category (which Glaucon takes third) contains things, activities, and experiences that are best thought of as means to an end external to them. We can think of such goods as instrumental rather than intrinsic goods. Glaucon takes them to be onerous but beneficial (2.357c), valued not in themselves but for the rewards and other things that come from them (2.357c). Physical training and medical treatment (and, it will later turn out, governing) are offered as examples of such instrumental goods. There is a certain subjectivity here, though, as some people find physical training enjoyable in itself, even apart from its instrumental benefits. Some people love running, for example, enjoying the activity itself; others loathe it, valuing it only for the benefits it brings. We might put the difference this way: the lovers enjoy running, while the loathers enjoy having run. Flossing ones teeth seems an everyday example of an onerous but beneficiali.e., purely instrumentalgood: we do it not because it is enjoyable in itself, but because of its good results: healthier gums and fewer lectures about the importance of flossing from finger-wagging dentists. But a person who enjoys the activity itself is not making a mistake; they merely have preferences and tastes that are not widely shared. The third kind of good (which Glaucon takes second) is mixed, comprising intrinsic and instrumental goods: a kind of good we like for its own sake and also for the sake of what comes from it (2.357c). For A Fresh Start 59 some people, physical exercise is completely a second-category good, onerous but beneficial: instrumentally good but intrinsically bad. But for others it belongs to this third, mixed category: one recognizes the health benefits of running five miles every day, but one also enjoys the activity itself. And perhaps watching that sunset relaxes you and lowers your blood pressure, so it too might be a mixed good. Glaucon and Socrates regard goods of this third category as the best kind of goods, since they combine both intrinsic and instrumental goodness. It might be that the drive to the golf course is lovely and thus valuable both intrinsically, since you enjoy it in itself, and also instrumentally, since it is an efficient way to get to the golf course. Where does justice belong? Most people, Glaucon says on behalf of Thrasymachus, place it in the second category of things and acctivities that are intrinsically bad but instrumentally good, to be valued not for their intrinsic features but for the external benefits they bring especially the benefits of having a reputation for being just: most people [] say that justice belongs to the onerous kind, and is to be practiced for the sake of the rewards and popularity that come from having a reputation for justice, but is to be avoided because of itself as something burdensome (2.358a). Socrates and Glaucon, by contrast, think justice is the best kind of good, belonging in the third, mixed category, to be valued [] both because of itself and because of what comes from it (2.357e). Even though acting justly will not always be easy, its being challenging does not make it onerous, something one wishes one did not have to do, any more than running a marathon is onerous and to be avoided in virtue of its being difficult or challenging. The question of justices proper categorization shapes the rhetorical strategy of the rest of the Republic in an important way. Most people only halfway agree with Glaucons classification of justice. They concede the instrumental value of having a reputation for justice, of seeming to be just, but they deny justices intrinsic value, holding that being just is not by itself good. Thus what Glaucon and Adeimantus want from Socrates is to show them that a just life is intrinsically good: all by itself, it makes its possessors life go well. There is no need to try to show that a reputation for it is instrumentally good, since that is conceded on all sideseven Thrasymachus could agree with this. To show that justice is intrinsically good, they need to find a way to bracket off and ignore its instrumental 60 Platos Republic: An Introduction value; if they do not do this, they cannot be sure that justice is being valued intrinsically, in and for itself, rather than for its extrinsic benefits. Thus it will not be enough to compare the just and unjust persons. To ignore the instrumental benefits a reputation for justice brings, Socrates must draw on the distinction between being and seeming and saddle the just person with a reputation for injustice. If he can show that the person who is just but seems unjust is happier than the person who is unjust but seems just, he will have shown that justice is intrinsically goodthat all by itself it makes its possessors life better. Glaucons Three Thrasymachan Theses (2.358a362c) Let us now turn to the second prong of Glaucons challenge, his devils advocacy of Thrasymachus view. We should pause to appreciate what good intellectual practice Glaucon models here. To understand an opponents view well enough to be able to state it clearly and forcefully and fairly is not easy, but it is a hallmark of intellectual fairness. Most of us are more familiar with someones arguing against a view by presenting and then rejecting a caricature of the view in question. To argue this way is to commit what is known as the strawman fallacy (so-called because strawmen and -women are so easy to knock over). To take an obvious contemporary example, consider arguments about the morality of abortion. Most of us have probably heard arguments like these: Of course abortion is immoral; those who think it is not seem to think it is okay to murder babies and Of course abortion is permissible; those who think it is not seem to think a woman should have no right at all to decide what happens to her body. Both of these arguments commit the strawman fallacy: it is a safe bet that no defender of the moral permissibility of abortion takes pleasure at the thought of murdering babies; nor does the typical opponent relish the opportunity to interfere with a womans bodily autonomy. Indeed, the phrase they seem to think that is a fairly reliable indicator that a strawman fallacy is coming your way. Now it may be that strawman characterizations are rhetorically effective; they are no doubt good ways to energize the base. But they are intellectually debased ways of providing reasons in support of ones view, whatever that view may be. There is nothing wrong with arguing for ones view by arguing against an opponents A Fresh Start 61 view, but intellectual integrity requires that we characterize the opponents position fairly and charitably, such that they will recognize it as theirs and that it appears to be a view that a reasonable person might hold, rather thanas seems sadly typicala view that only a morally corrupt, irrational person would find compelling. Thrasymachan Thesis #1: Justice is Conventional, Not Natural (2.358e359b) The distinction between nature ( [phusis], whence the word physics) and convention ( [nomos], whence words like economics) is common in the Republic. In one sense, what is natural is what is real or true independently of what anyone thinks or does, while what is conventional is true or real only in virtue of a decision one or ones culture makes. The difference between rivers and trees is a natural difference, not a conventional one; but borders between states are matters of convention, even when the border is a natural object such as a river. In a different but related sense, a things nature is what makes it the kind of thing it isa knife rather than a fork, a plant rather than an animal, etc. In his Physics, Aristotle said that a things nature is its internal principle of change and stability, and what is natural to the thing is to follow this internal principle.2 Although most acorns will not become oak trees, becoming an oak tree is natural to an acorn in this sense. In claiming on behalf of Thrasymachus that justice is not natural but a matter of convention, Glaucon is suggesting that injustice is what comes naturally to us; left to our own devices, we strive to outdo our fellows without regard to the propriety of doing so. But since we weak folks fear being treated unjustly, we band together and take power, inventing the rules of justice to protect ourselves against the more powerful, who are fewer and can be subjugated by the many. Thus justice is conventional, not natural: it is an invention, imposed upon us from without, existing only as the result of intentional human activity and choice. The basic picture will be familiar to readers acquainted with the great seventeenth-century British philosopher, Thomas Hobbes. Imagine a world before law and civilization. In this state of nature, Hobbes 2 Aristotle, Physics, II.1 192b2023. 62 Platos Republic: An Introduction thought, we have complete freedom to do whatever we want to do; there are no moral or legal restrictions on ones conduct. The good news, then, is that you can do whatever you want to do: take someone elses stuff, kill them if you feel so inclined, etc. The bad news, of course, is that everyone else can do so as well. Life in the state of nature, Hobbes said, is solitary, poor, nasty, brutish, and short. There is no right to life in the state of nature, understood as a claim-right or entitlement not to be killed, which imposes a duty on others not to kill. But most of us, Hobbes plausibly thought, are willing to give up some of the total freedom we have in the state of nature in exchange for the sort of security a right to life brings. I agree not to kill you and take your stuff but only on the condition that you agree to do the same for me. Thus is civil society, and indeed morality, born. Justice, on this view, is the result of a bargain; it is an invention, and thus conventional rather than natural. Only a fool, Thrasymachus and Hobbes think, would altruistically refrain from killing and taking from others without getting a corresponding guarantee in return. Most of us find it to our advantage to come to an agreement with each other neither to do injustice nor to suffer it and thus we make laws and covenants, and what the law commands [we] call just and lawful (2.359a). (Hobbes takes an additional step not mentioned by Thrasymachus or Glaucon, holding that there must be an authority to settle disputes and enforce the social contract, but we need not linger over this point.) On this Thrasymachan view, justice is not natural in either sense distinguished above. Far from being mind- or culture-independent, it is something we invent rather than discover, and there is nothing more to it than the rules agreed to. Thrasymachus expressed such a view in Premise 2 of the Error Argument back in Book I. Moreover, it is injustice, he holds, and not justice, that comes naturally to us. Injustice is what anyones nature naturally pursues as good (2.359c), on the Thrasymachan view. The ideal of masculinity implicit in this view of justice will seem to many a toxic one: a true man, Glaucon says, wearing his Thrasymachan mask, would not make an agreement with anyone not to do injustice in order not to suffer it (2.359b). He would not make such an agreement because he would not have to: the Thrasymachan man is able to impose his will on his fellows in the state of nature; he has no need of rules restraining his natural inclinations to A Fresh Start 63 outdo others, since he is powerful enough not to fall victim to others attempts to outdo him. (Later in the Republic Plato will criticize this picture of masculinity, but for now it is part of the Thrasymachan picture Glaucon is painting.) Even though most of us lack this kind of strength and power, if enough of us band together we might be more powerful than the Thrasymachan true man. If so, we can make rules to protect ourselves against him, since moralityor, rather, morality is merely the mechanism by which the powerful protect their interests. But if this group of individually weak but collectively strong people is driven by self-interest, it is unlikely to extend the protections of morality to those whom it can exploit for its own ends. This brings us to the second thesis. Thrasymachan Thesis #2: Those Who Act Justly Do So Unwillingly (2.359b360d) The second thesis is intimately connected with the first. Since injustice comes naturally to us and justice is unnatural and artificial, acting justly is contrary to our natural inclinations; it goes against our grain because the desire to outdo others and get more and more [] is what anyones nature naturally pursues as good (2.359c). On this view, people who act justly do so unwillingly; if they could get away with acting unjustly, they would. And in fact the artifice of justice does not merely go against our nature, it distorts it: nature is forced by law into the perversion of treating fairness with respect (2.359c). This is a pretty bleak view of human nature and of the nature of morality, but it has an undeniable plausibility. But Glaucon does not rely merely on forceful language to garner agreement, he gives a famous argument for it: the Ring of Gyges Argument, important both for its content but also for the kind of argument it is. The ring in question belongs not to Gyges but to an ancestor of his, so the argument is misnamedbut that does not really matter to the point at hand, which is Thrasymachan Thesis #2. Gyges ancestor happens upon a ring with magical powers: when he turns it in a certain direction, he becomes invisible. What does he do with his newfound power of invisibility? He seduces the queen, kills the king, and takes over the kingdom. The key move in the argument happens next: imagine, says Glaucon, that there 64 Platos Republic: An Introduction is another such ring; what do you think its wearer would do? Would they be so thoroughly, incorruptibly moral that they would not take advantage of the situation to enrich themselves at the expense of others? If you think the wearer would act unjustly because they can do so with impunity, you should agree that the second thesis is true. We act justly only because we think we have to, Thrasymachus thinks, not because we want to; if we could act immorally and get away with it, we would do just what Gyges ancestor did. Glaucon has offered a thought-experiment, which is a very common way of doing philosophy: here is a fanciful scenario, what do you think about it? What is the right thing to do? Philosophical inquiry is rife with thought-experiments: Would you throw the switch to divert a runaway trolley car from a track on which it will kill five workers to a track on which it will kill only one? If you were kidnapped by the Society of Music Lovers and awoke with your kidneys connected to those of a famous violinist who will die if you disconnect yourself, are you morally permitted to disconnect yourself, resulting in the violinists death?3 Etc. There is certainly a place for thought-experiments in philosophical thinking, and their artificiality is no objection to them; they are not intended as realistic situations we encounter in our everyday lives but rather bear certain similarities to situations we do encounter in ordinary life: if you think disconnecting yourself from the violinist is permissible, should not you also think that it is permissible for a woman to terminate an involuntary pregnancy? Thought-experiments are common in philosophyand in theoretical physics, too (just ask Schrdingers cat)but when fundamental claims about human nature are at issue, perhaps thought-experiments should yield to fields like evolutionary biology and psychology. That the Thrasymachan takes it to be obvious that most people think they would act as Gyges did if they had the chance might tell us a lot about the culture these Thrasymachans inhabit, even if it does not establish any trans-cultural truths about human nature. But that is probably all it is intended to do here: Thrasymachan Thesis #2 articulates a widelyheld view of human nature, one that Glaucon thinks is false and that he wants Socrates to refute. 3 Judith Jarvis Thomson, A Defense of Abortion, Philosophy & Public Affairs, 1 (1971), 4766 (pp. 4849). A Fresh Start 65 Thrasymachan Thesis #3: The Unjust Person is Happier than the Just Person (2.360e362c) This of course is Thrasymachus answer to the second of the Republics two main questions, whether the just or unjust life is happier, which Socrates realized that hed tried to answer before answering the first one. What is most relevant here are the constraints Glaucon proposes for answering it. If the unjust person is really going to outdo everyone, they will find that having a reputation for justice will greatly help them use the rules of justice to exploit others: they will find that they are more effective at being unjust if they seem just. No one who thought that Bernard Madoff was a conman running a Ponzi scheme would have invested with him; his cheating his investors out of billions of dollars was made possible in no small part by his sterling reputation. The last third or so of the Republic is devoted to assessing this third Thrasymachan thesis; Glaucon is here stating it, not arguing for or against it (though we do know that he actually thinks it is false, devils advocacy aside). Instead, he is setting the parameters for how Socrates is to defeat this thesis. Harking back to the distinction between kinds of goods, Socrates and company think that most people regard justice as onerous but beneficial: bad intrinsically but good instrumentally, especially the reputation for justice. Glaucon and Socrates think justice is both intrinsically and instrumentally good, but since even skeptics agree with them about its instrumental value, what Socrates needs to do is to show that justice is intrinsically good: that all by itself, a morally good life benefits the person living it, and indeed is better for them than a morally bad life, even if they do not get any of the extrinsic, instrumental benefits. We need to bracket off the instrumental benefits of having a reputation for justice because if we do not find a way to ignore them, we cannot be sure that we are valuing justice intrinsically, in and of itself, and not for the instrumental benefits a reputation for justice brings: we must take away his reputation, for a reputation for justice would bring him honor and rewards, so it would not be clear whether he is just for the sake of justice itself or for the sake of those honors and rewards. We must strip him of everything except justice and make his situation the opposite of an unjust persons. Though he does no injustice, he must have the greatest reputation for it, so that his justice may be tested fullstrength and not diluted [] (2.361c) 66 Platos Republic: An Introduction So in settling the question of which life is happier, we must draw not only on the distinction between intrinsic and instrumental value but also on the distinction between appearance and reality. Glaucon will regard his belief that the just life is happier as justified only if Socrates can show him that the person who really is just but seems unjust is happier than the person who is unjust but seems just. It is quite a tall order, as Socrates recognizes, but it is the only way they can think of to separate off the intrinsic goodness of justice from its instrumental, reputational benefits. If Socrates can show us that the really just but apparently unjust person is happier than the really unjust but apparently just person, he will have shown us that justice is intrinsically good, since he will have shown that being just in and of itself makes one better off. If he can do this, he will have justified Glaucons presumably true belief that the just life is happier and thereby transmute his belief into knowledge. Adeimantus Ups the Ante (2.362d367e) Glaucons brother Adeimantus thinks that Glaucon has left out the most important thing (2.362d), which he takes to be the way justice is treated in Athenian popular culture. Adeimantus attention to culture shapes the Republic by anchoring Socrates focus on education in the ideal city that they will soon start constructing, if only in theory. His complaint is that Athenian culture and Greek culture more broadly, dont praise justice in itself, [but] only the high reputations it leads to and the consequences of being thought to be just (2.363a). He worries about the effect of such a culture on the souls of young people (2.365a), when they see through their cultures shallow platitudes to the deeper antirealist view that injustice [] [is] shameful only in opinion and law (2.364a) and not in itself. Agreeing with Thrasymachus about the value of being unjust but recognizing the importance of seeming just, they will become cynical and hypocritical, desiring to cultivate only a faade of illusory virtue (2.365c) rather than a genuinely virtuous character. The stories Athenian culture tells about the gods, such as the ones we find in Homers Iliad or Odyssey or Hesiods Theogeny, suggest that the gods can be influenced by prayers, sacrifices, and offerings. It is more profitable, on the Thrasymachan view of individual happiness, A Fresh Start 67 to reap the benefits of acting unjustly, and then toward the end of ones life to seek absolution by building a temple or making many sacrifices, thus avoiding the just deserts of a life of injustice. Although there will be a few people of godlike character who [are] disgusted by injustice (2.366c), most of us will find the allure of material success too attractive to resist. Some of us will feel guilty or ashamed, but othersperhaps because we will feel guilty or ashamedwill laugh aloud when we hear justice praised (2.366b), since, like Thrasymachus, we think justice is for suckers. Thus it is vital, Adeimantus thinks, for Socrates to show that justice is intrinsically good and to ignore any benefits that might accrue to someone with a reputation for justice. He wants Socrates to swim against the tide of Athenian culture and show them that injustice is the worst thing a soul can have in it and that justice is the greatest good (2.366e). Only if Socrates does this will Glaucon and Adeimantus be justified in their belief that the just life is happieronly then will that belief become knowledge. Socrates Plan: Investigate Personal Justice by Investigating Political Justice (2.367e369a) Socrates way of responding to Glaucon and Adeimantus request for a fresh defense of the just life will resonate with anyone who needs drugstore reading glasses to deal with a restaurant menu. Just as it is easier to read larger than smaller letters, Socrates argues (2.368d), it will be easier to figure out the nature and value of justice if we see it on a larger scale. So the plan is to examine the nature and value of justice writ large, in a polis (city-state), in order to see what it tells us about justice in a person: let us first find out what sort of thing justice is in a city and afterwards look for it in the individual (2.369a). This method of investigation is apt to strike many readers as odd, since it assumes an analogy between persons and cities that will seem a stretch to many. The analogy has certainly intrigued philosophical commentators on the Republic. Socrates is assuming that justice in individuals and justice in city-states do not differ in any relevant ways. A person (more properly, their soul) and a polis differ in size and thus so too does the amount of justice each contains, but the amount of justice is not relevant to its 68 Platos Republic: An Introduction nature, Socrates assumes, any more than a glass of water differs in nature from a gallon of water: water is water, regardless of how much of it there is. As we move forward, we will want to keep in mind the big if at the heart of Socrates method: if people and city-states are relevantly similar, then what we learn about the nature of justice in the latter can be mapped onto the former. We will see in Book IV that Socrates will try to do more than just assume they are similar; he will argue that they are. But for now, let us grant the analogy and see what Socrates does with it. A False Start: Socrates Rustic Utopia (2.369b373a) Socrates plans to create a city in theory from its beginnings (2.369c), but of course it cannot be just any city; for the plan of the Republic to work, it must be a just city. And this city must not only be just, if they are to determine the truth about the nature and value of justice, it must also seem just to Glaucon and company, if they are to be persuaded that the just life is the happier life. Once all agree that the theoretically constructed city is just, the task will be to determine the nature of the virtue of justice, or what makes it just. We should note too that since Plato wants his readers to imaginatively participate in the dialog, readers will have to determine for themselves whether they find the city Socrates has created to be just (which, remember, is synonymous with being morally good, generally). Readers who do not think the ideal city is just or who are not sure can still follow the argument in a hypothetical way: Well, if this were a just city, does Socrates plausibly explain what makes it just?. But this will be less than fully satisfying, especially if, like Glaucon and Adeimantus, we want Socrates to provide us with reasons we find plausible that would justify the belief, if indeed we hold it, that the just life is a better and happier life than the unjust life. The origin of any community, Socrates thinks, is that none of us is self-sufficient (2.369b). It is not just that we have needs, but we have needs that we cannot ourselves always meet. Thus, he thinks, communities are formed: people gather in a single place to live together as partners and helpers (2.369c). This idea of cities as essentially cooperative is an attractive one, and it is at odds with the Thrasymachan view of cities as sites of competition rather than cooperation, where citizens are always A Fresh Start 69 trying to outdo each other. Perhaps Thrasymachus could agree with Socrates about the cooperative origins of any polis while thinking that people will strive to outdo each other once a city is up and running. People will always strive to exploit others neediness for their own advantage, and crafty Thrasymachans will be more successful at doing so than others. Socrates next argues for a division-of-labor principle that will not only organize the citys economic life but will ultimately have profound ethical implications, as it will be the basis of the definition of justice he arrives at in Book IV. We are all born with different natural aptitudes and preferences, he thinks, each of us having a distinctive [ergon] or natural task or function, a notion we met in Book I, most notably in the Function Argument. Since we are born with different aptitudes, Socrates advocates a division of labor: more plentiful and better-quality goods are more easily produced if each person does one thing for which he is naturally suited [] and is released from having to do any of the others (2.370c). At least two things about the argument for what we will call the Specialization Principle are worth attending to. The first is the way Socrates appeals to what he takes to be natural facts in arguing for it, facts which many readers will find quite plausible. Many readers will have known people who have always been good at math, or who can quickly master a variety of musical instruments, or who have a knack with machines, or who excel at certain sports, etc. Though hard work and discipline are necessary for success in such areas, there usually is a natural aptitude at the core that can be developed and perhaps perfected by diligent practice and educationbut without the natural aptitude as the raw material which nurture can develop, the chances of high-level success seem slim indeed. The second feature is that Socrates advocates the Specialization Principle because it benefits the community as a whole, not because it enables individual flourishing. This is perhaps the first inkling of Socrates communitarian inclinations: he is likelier to think of the needs and good of the community first, in relatively sharp contrast to the tendency many contemporary Westernersespecially Americanshave to think individualistically. On this individualistic view, individuals are morally primary and communities exist primarily to enable individual flourishing or perhaps to protect the natural rights 70 Platos Republic: An Introduction individuals possess. The distinction between communitarian and individualistic thinking is a matter of degree and often context: a baseball team or string quartet comprising dyed-in-the-wool individualists who care more (or only) about their own individual successes will surely be less successful than teams or quartets with more group-minded members. In the riveting opening chapter of his novel, Enduring Love, Ian McEwan writes of moralitys ancient, irresolvable dilemma: us, or me.4 If McEwan is right, the fundamental moral question is not us versus them or me versus you but rather me versus we: do the needs and interests of the community trump the individuals? Far from regarding the dilemma as irresolvable, Plato and Socrates resolve it in favor of we over me. I suspect that many, if not most, readers will often find themselves resistant to and put off by Socrates communitarian, we-favoring impulses. Even so, there is much value in being confronted with thinking that is fundamentally different from ones own, as this not only provides alternative perspectives but also might force one to play Glaucon and Adeimantus and try to justify deeply-held beliefs that one takes for granted. There will be many occupations in the ideal city: farmers, builders, carpenters, shepherds, weavers, and cobblers, to name a few. There will also be importers and exporters, merchants, retailers, and physical laborers. Very quickly, in just a couple of pages, we learn that the ideal city is complete: our city [has] grown to completeness [ So] where are justice and injustice to be found in it? (2.371e). As Socrates begins to answer this question by examining the sort of lives its citizens lead, Glaucon objectsto the surprise of many readersto the food. The food is of the sort they cook in the country (2.372c), he complains, unsuitable for a young Athenian aristocrat, but perhaps suitable if you were founding a city for pigs (2.372d). Most readers are apt to be misled by this charge, since to modern ears talk of pigs suggests gluttony and perhaps uncleanliness. But this is not the connotation for ancient Athenians, for whom, Myles Burnyeat points out, the pig was an emblem rather of ignorance [] Any pig would know was the 4 Ian McEwan, Enduring Love (New York: Anchor Books, 1998), p. 15. A Fresh Start 71 saying. What Glaucon means is, You describe the feasting of people who do not know how to live. It is uncivilized.5 Socrates acquiesces and agrees to develop a luxurious city (2.372e) better suited to his young friends expectations about what a good life involves. He does not agree with them, as he quickly makes clear: the true city [] is the one we have described, the healthy one (2.372e). But he goes along with them because the plan of the Republic demands it. Glaucon and Adeimantus, remember, want Socrates to provide them with good reasons for a belief they sincerely hold but recognize to be unjustified, the belief that the just life is the happier one. If this requires that they give up their conception of what a good life isif justice requires that they live the simple, rustic life Socrates depictsthey are unlikely to be convinced by what he has to say. There is some interesting scholarly disagreement about whether and how seriously to take Socrates praise of the first city. Its benign anarchythere is no mention of any political structures or governmental officeswill appeal to many readers, as will its simplicity, its communal bonds, and its relative selfsustainability. But the ideal city they ultimately develop is structured by three natural classes (4.435b (italics added)), which suggests that the first city, which lacks them, is not natural after all. In any event, Socrates agrees to sketch a luxurious city, replete with the sorts of delicacies Glaucon and Adeimantus insist upon and, going well beyond the more basic necessities found in the first city, to include perfumes, prostitutes, and pastries (2.373a). More striking, though, than what the luxurious city includes is what follows in its wake: war. Having overstepped the limit of their necessities (2.373d), the citizens now require resources they do not possess, and now possess goods that other city-states might envy and seek for themselves. It is striking that Plato finds the origins of war (2.373e) not in an innately aggressive human nature; the explanation is social and economic rather than biological: communities come into conflict with each other when they exceed a simple, natural life and grasp for luxury (and here pleonexia rears its ugly, Thrasymachan head). If the first, rustic city is a real possibility, 5 Myles Burnyeat, Culture and Society in Platos Republic, in The Tanner Lectures on Human Values, vol. 20 (Salt Lake City: University of Utah Press, 1999), p. 231. Italics in the original. (Burnyeats lecture and dozens of others can be found online at https://tannerlectures.utah.edu/lecture-library.php). 72 Platos Republic: An Introduction then acquisitive, me-first pleonexia is not what comes naturally to human beings. Obviously, with warfare comes the need for soldiers, but Socrates eschews the idea of citizen-soldiers in favor of a professional army. Warfare is a profession (2.374b), he argues, and according to the Specialization Principle only someone with a natural aptitude for warfare should become a soldier. But the ideal soldier must naturally be both gentle and high-spirited (2.375c), tough with foes but gentle with friends. Socrates initially despairs of finding such a combination, worrying that these traits are so at odds with each other that it seems impossible to combine them and thus that a good guardian cannot exist (2.375c). His despair vanishes, though, when he thinks of dogs, whom he delightfully regards as truly philosophical (2.376b), since their conduct is knowledge-based. Dogs treat people differently based on whether they know the person or not: friends are proper objects of gentleness, while strangers or foes are not. Of course, not all dogs make good watchdogs: some are too gentle and sweet by nature, others too aggressive, even with family members. Since gentleness and high-spiritedness are often at odds with each other, proper education will be crucial to the soldier-guardians proper development and thus to the flourishing of the city. So once we have found someone who seems to possess a natural aptitude for guarding the city (in the case of soldiers) or the home (in the case of dogs) the question is this: how are we to bring him up and educate him? (2.376c). This is the question to which we turn in the following chapter. Some Suggestions for Further Reading Readers interested in a philosophically sophisticated account of Glaucons division of kinds of goodness will find C.D.C. Reeve, Philosopher-Kings: The Argument of Platos Republic (Indianapolis: Hackett Publishing, 2006), pp. 2432 challenging but rewarding. I first encountered the distinction between instrumental and constitutive means in J. L. Ackrill, Aristotle on Eudaimonia, in Essays on Aristotles Ethics, ed. by Amlie Oksenberg Rorty (Berkeley and Los Angeles: University of California Press, 1981), pp. 1533. The golf example appears on p. 19. A Fresh Start 73 Readers interested in Hobbes political philosophy will find helpful Sharon Lloyd and Susanne Sreedhar, Hobbes Moral and Political Philosophy, in The Stanford Encyclopedia of Philosophy, ed. by Edward N. Zalta, https://plato.stanford.edu/entries/hobbes-moral/ Readers interested in the scholarly discussion of the city-soul analogy will find no better place to start than Bernard Williams, The Analogy of City and Soul in Platos Republic, in Platos Republic: Critical Essays, ed. by Richard Kraut (Lanham, MD: Rowman & Littlefield, 1997), pp. 4959. G. R. F. Ferrari, City and Soul in Platos Republic (Chicago: University of Chicago Press, 2005) devotes itself to the city-soul analogy as well as attempt[ing] to say what Plato is getting at in the Republic (p. 9), which it does in lucid, lively prose. For readers interested in the scholarly debate around the first city, an excellent place to start is Rachel Barney, Platonism, Moral Nostalgia and the City of Pigs, Proceedings of the Boston Area Colloquium in Ancient Philosophy, 17 (2001), 20727, https://doi. org/10.1163/2213441790000032. Readers interested in making sense of Glaucons food-based objection to the first city in particular and Athenian life around Platos and Socrates time in general will delight in James Davidson, Courtesans and Fishcakes: The Consuming Passions of Classical Athens (New York: St. Martins Press, 1997), which is lively and engaging. Figure of a boy writing on a kylix, 480 B.C. Photograph by Reame (2019), Wikimedia, CC BY-SA 4.0, https://commons.wikimedia.org/ wiki/File:Figura_ragazzo_che_scrive_su_kylix.jpg#/media/File:Figura_ ragazzo_che_scrive_su_kylix.jpg 4. Blueprints for a Platonic Utopia : Education and Culture, Books II and III In having Socrates work out the proper education for the would-be guardianswhich at least initially must include all the citys children Plato engages in the philosophy of education for the first time in the Western philosophical tradition. He is not the first philosopher to do so, as readers familiar with non-Western philosophy will know. Confucius Analects, which predates Platos Republic by almost a century, devotes considerable attention to the nature and value of education and in fact begins by celebrating it; indeed, the first word The Master is quoted as saying is xue (), which means learning or study. Education is a topic of sustained focus in the Republic. In Books II and III Plato sees education as a two-pronged endeavor, comprising physical training for bodies and music and poetry for the soul (2.376e). A little later, he will reconsider this way of thinking about educations objects, holding that physical training and poetic education are both chiefly for the sake of the soul (3.410c). Later in the Republic, while developing the famous Allegory of the Cave in Book VII, Plato has Socrates give an account of formal education involving arithmetic, geometry, astronomy or physics, and dialectic, a sort of philosophical logic, more or less inventing what has come to be known as liberal education. In Books II and III, however, the focus is on educations less formal aspects, education in the wider sense of the Greek word (paideia): upbringing or enculturation. Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.04 76 Platos Republic: An Introduction Supervising the Storytellers: Musical and Poetic Content (2.376c3.392c) Socrates is especially concerned with the effects of popular culture on the development of character, both of the would-be soldier-guardians and of the citizenry at large. We begin absorbing our culture, which is carried by the songs sung in the home and in public, so Socrates first focuses on the storiesliterally the myths ( [muthoi])children hear in the songs sung to and around them. Many readers will shrink at Socrates insisting that the first thing he and his fellow theoretical architects must do is supervise the storytellers (2.377b). But even those of us who value freedom of speech and artistic expressiontwo values conspicuous by their absence in the Republicprobably do not think that all books or movies or television shows or videogames or music are appropriate at all ages. But while most readers will likely think this is a private matter, to be determined by parents, for Plato it is too important to be left to individual discretion (and thus is another of those places where his community-mindedness is evident). After all, the explicit point of education is to develop good soldier-guardians, which is surely a matter of public and not merely private concern. At the root of Platos educational program is a belief in the malleability of the human psyche, especially at young ages: You know, dont you, that the beginning of any process is most important, especially for anything young and tender? Its at that time that it is most malleable and takes on any pattern one wishes to impress upon it (2.377b). Hence the need to regulate the stories children hear, both their content and their form. Socrates focuses first on the former, on what the stories say, and then in Book III he focuses on how the stories are told, on their form. The most important restriction on the content of stories is that they must not convey true falsehoods, which are falsehoods [] about the most important things (2.382a). The phrase true falsehood is easy to trip over, since it suggests the idea of stories that are literally false but convey moral truths. This is emphatically not what Socrates means; true here means real or genuine; a true falsehood is something that is deeply, genuinely false. Socrates is not anti-fiction; he is not opposed to nursery rhymes that contain literal falsehoods, or what he calls falsehood in words (2.382c). That there never was a person who lived in a shoe or a Blueprints for a Platonic Utopia 77 race between a tortoise and a hare is not important, so long as the storys underlying moral message is not radically false. There are three categories of stories whose content should be regulated: stories about the gods, stories about epic heroes, and stories about people. Socrates rightly avoids regulating the last kind of story at this stage of the Republic. Presumably, he regards Thrasymachus claim that the unjust life is happier than a just life as a true falsehood: it is deeply, profoundly mistaken and soul-distorting, and it ruins anyone who steers their life by it. But to rule out such stories now, before the Republics two questions have been satisfactorily answered, would beg the questionthat is, it would assume the truth of what he should be trying to prove. It would be intellectually unfair to adopt a regulation banning such stories in his ideal city, since he is not yet entitled to claim that Thrasymachus is mistaken. As the gods are among the most important things, we must be on guard against true falsehoods regarding the gods. There are two restrictions on stories about the gods: first, that the gods are not the cause of everything but only of good things (2.380c); second, that the gods are not shape-shifters or deceivers who mislead us by falsehoods in words or deeds (2.383a). Since a god is by nature good, and what is good cannot cause something harmful and bad, a god cannot be the cause of bad things. So any story saying otherwise is promoting a true falsehood and should be disallowed, even if Homer or Hesiod or any canonical Greek poet is its author. The same goes for stories depicting gods as deceivers. Since the best things are least liable to [] change and the gods are among the best things, they would not alter their appearances or have any need to speak falsely (2.380e). We might question the chains of argument by which Socrates arrives at these conclusions. For example, he never considers the possibility that there are no gods, or the possibility that a god might lie for good reasons. But the real take-aways here are not the particular content of any rules he arrives at, but rather three key ideas: first, that one should not uncritically accept the norms and values of ones culture; second, that reason provides a perspective from which cultural norms and values can be assessed; and third, that if there is a conflict between culture or tradition and reason, we should follow the dictates of reason. Although his community-first ethos is often associated with a kind of 78 Platos Republic: An Introduction conservatism that prizes tradition and the wisdom embodied therein, Socrates is no conservative. Far from it. He is a radical rationalist, believing that rationality affords a perspective from which a traditions practices and values can be assessed. Socrates loves Homer, but he thinks that his passion for poetry must give way to what reason tells him about it. Hence he goes through Homer and Hesiod with an editors pen, striking passages that cannot stand up to rational scrutiny, much as someone might go through the Bible or Koran striking out passages they took to express true falsehoods. (Thomas Jefferson seems to have been up to something similar in The Life and Morals of Jesus of Nazareth, in which he excised all mention of Jesus divinity, his performing miracles, resurrection, etc.) Much as censoring stories about the gods is designed to foster the virtue of piety, censoring stories about epic heroes is meant to foster the secular virtues of courage and moderation. If would-be guardians are to acquire the courage-grounding belief that there are things that are worse than deathslavery and dishonor, to name twothey must not be exposed to stories about the horrors of Hades or of heroes lamenting the loss of loved ones. The same goes for moderation (also known as temperance): if young people are to become temperate, they must have exemplars to imitate, which they will not have if they are exposed to stories showing heroes over-indulging in food, drink, and sex, or desiring money or acting arrogantly or being overcome by anger or even laughter. Socrates point here is that ones culture provides models of appropriate behavior, models that we internalize from a very young age. Although the reasoning is not conscious, the process seems to go something like this: we hear stories of gods acting dishonestly or heroes wailing about death and infer that these are appropriate ways for us to behave. Everyone will be ready to excuse himself when he is bad, Socrates argues, if he is persuaded that similar things [] have been done in the past by close descendants of the gods (3.391e). Hence it is vitally important that one be exposed to good models right from the start, where good models does a double duty: good models of good people. That Athenian culture fails in this regard, that its stories traffic in models of clever people acting unjustly and getting away with it, is Adeimantus complaint. Blueprints for a Platonic Utopia 79 Supervising the Storytellers: Musical and Poetic Style (3.392c401d) One of the fascinating features of Socrates account of education broadly construed is that it attends not merely to the content of stories and songs, as we might expect, but to their form or style, as well. The main idea is that a songs musical modenot exactly equivalent to our notion of key but close enough for our purposesand its meter or rhythm affect us independently of its words. This issue is connected to a longstanding debate in the philosophy of music about whether music contains emotions or merely excites themwhether, for example the second movement of Schuberts Sonata in A major is sad in itself or whether the sadness is merely evoked in us by the music, which is itself emotionally unladen. How music could encode emotions is a fascinating question, but it is one we need not address here, since what Plato has Socrates say does not requirethough it is consistent withthe view that music contains and encodes emotion rather than merely evoking it in listeners. While Greek musical modes are not identical to keys in Western music, thinking about keys can help us get a sense of how different modes have different emotional tones. The internet can be a great help here, since YouTube is rife with songs in which the key has been shifted from major to minor or minor to major. Consider the Beatles classic, Hey Jude, originally written in F major. Transposed to F minor, it is a very different song: sad, pensive, almost dour. Upbeat pop songs like Cyndi Laupers Girls Just Want to Have Fun or Cheap Tricks I Want You to Want Me sound sad and ironic when transposed from their original major to the corresponding minor key. Regardless of whether one stands or kneels for The Star-Spangled Banner before a professional football game, it seems like a different song when sung in a minor key. It works the other way, too: R.E.M.s Losing My Religion sounds happy and optimistic when modulated into A major, as does the theme from The Godfather. The lesson here is that the keyor, for Plato, modein which a song is sung matters. So in addition to wanting to delete the lamentations and pitiful speeches of famous men (3.387c), since they cultivate cowardice and indulgence rather than courage and temperance, Socrates also wants to do away with the lamenting modes (3.398e) in his ideal city, since 80 Platos Republic: An Introduction even without lamenting lyrics, these modes will convey or cultivate these vices, too. The soft modes suitable for drinking parties (3.398e) are out, too. What remains are the mode that would suitably imitate the tone and rhythm of a courageous person who is active in battle and another mode, that of someone engaged in a peaceful, unforced voluntary action [] acting with moderation and self-control (3.399b), since these modes will cultivate the emotions and thus virtues proper to the would-be guardians. Socrates pays similar attention to rhythm and meter, aiming to cultivate grace and avoid gracelessness (3.400c). It is important to see that the restrictions on form and style are not afterthoughts, secondary to the restrictions on content. They are in fact more basic, since we are exposed to music well before we can understand the words of the songs our families and fellow-citizens sing to and around us. Rhythm and harmony, Socrates says, permeate the inner part of the soul more than anything else (3.401d). Before we can understand the words of songs, we are shaped by their modes and rhythms, and indeed the shaping done by rhythm and harmony is even more important, Socrates thinks, since it begins to work on us at once. The point of proper aesthetic education here is not to come to have knowledge about the beautiful, but rather to come to know it directly, to recognize it when we hear and later see it. The Aesthetically Beautiful and the Morally Beautiful (3.401d403c, 412be) At least three other features of Platos account of aesthetic development are worthy of our attention. The first is that our aesthetic education is in fact the beginning of our moral education. Plato does not draw a sharp line, as we moderns tend to, between the beautiful and the morally good. While other approaches to ethics focus on duty and action (for example, the ethics embodied in the Ten Commandments, replete as it is with Shalts and Shalt Nots, and in the modern era Kants duty-based deontology), Platos ethics takes virtue to be central. For a virtue-centered ethics, the fundamental question is not What should I do? but What kind of person should I be? Where duty is essentially imperative, placing demands upon us, virtue is essentially attractive, Blueprints for a Platonic Utopia 81 expressing ideals of character that we can approach by degreesand, if Plato is right, that we are drawn to precisely because it is beautiful ( [kalon]). Where Kant thought one should be motivated by duty to do ones duty, Platoand here I am making the safe bet that he would agree with his student Aristotle, who is much more explicit about this than his teacherholds that the proper moral motivation for performing a certain action is that the action is fine or noble or beautifulthat it is kalon, which seamlessly combines aesthetic and moral notions. Our moral education begins with our aesthetic education because, Plato thinks, proper exposure to beautiful modes, harmonies, and rhythms will cultivate the right distastes and tastes (3.401e) in young people. This is not so they will become cultured aesthetes devoted to the aesthetically beautiful, but rather so they will be able to recognize and become devoted to the morally beautiful. In learning to recognize ugly sounds as ugly we come to learn to recognize shameful actions as shameful. It is no accident that the same Greek word (aischros) means both ugly and shameful. Socrates regards doing injustice as shameful, but the Thrasymachan strongmanand anyone whose moral sensibilities have not been properly cultivatedhas no scruples about doing injustice (2.362b), since he does not find the very idea repellant. Without radically altering the kind of upbringing and education Athenian popular culture will produce, young people will not be disgusted by injustice (2.366d) but will try to get away with it when they can. A second important feature is that proper musical education will inculcate correct moral beliefs while [we are] still young and unable to grasp the reason (3.401a). In other words, we will learn that certain traits and actions are admirable while others are notbut this will not teach us why the morally admirable traits are admirable. For that, we need philosophy. As I have noted already, this is essentially Glaucons and Adeimantus position: they believe that justice trumps convenience and self-interest, that the just life is happier than the unjust life, etc., but they recognize that they cannot justify these beliefs. But this underlying moral substrate of proper tastes and distastesin a word, proper moral sentiments or feelingsis absolutely essential, on Socrates view. Children who develop in a musically corrupt culture will fail to acquire the correct moral beliefs, because of the false models of beauty they will internalize. 82 Platos Republic: An Introduction A third feature, closely related to the second, is that properly educated children will love what is beautiful and good. Education in music and poetry, says Socrates, ought to end in the love of the fine and beautiful ( [kalou ertia]) (3.403c). It is well worth noting that the love there is erotic love: they are in love with what is noble and fine, with what is morally beautiful. So, underlying any cognitive, philosophical grasp of justice is a pre-rational, emotional attachment to it. This comes to the fore later in Book III when Socrates, in addressing the question of who should rule, separates off the guardians from the auxiliaries. We will say more about this in a bit, but it is worth bringing out the connection between love and governing. The rulers must be the best of the guardians (3.412c), Socrates thinks. But in the Book I conversation with Polemarchus he said that the best guardian of something is also its best thief (1.334a). What keeps these guardian-rulers from stealing the cityfrom going Thrasymachan, so to speak, and using their power to benefit themselvesis that they love the city? The right kind of love (the orthos ers) that is the product of proper musical education is the love of order and beauty (3.403a). In loving the city, the guardians identify its good with theirs: someone loves something most of all when he believes that the same things are advantageous to it as to himself and supposes that if it does well, he will do well, and that if it does badly, then he will do badly too (3.412d). Love certainly has an affective or phenomenological dimension: it feels a certain way. The variety of poems and pop songs devoted to what love feels like attests to the difficulty of describing the feeling in a non-metaphorical way: love is like a heatwave, love is a flame, etc. But in stressing the belief at the core of love, Plato plays down its affective dimension and plays up its cognitive dimension. We should note an asymmetry to the belief at the heart of Socratic love. In loving you, I identify my wellbeing with yours: I take what is good for you to be good for me. Taking what is good for me to be good for you is another way of creating an identity between your wellbeing and mine, but it is a defective form of love if it is a form of love at all. Many readers know sadly, some know through first-hand experienceparents who force or at least foist their wellbeing and conceptions of what a good life is onto their children, insisting that the child act for the sake of the parent. In addition to this asymmetry in belief, we should note that love requires Blueprints for a Platonic Utopia 83 something more than this belief and a feeling of fondness. In addition to loves cognitive and affective dimensions, there is also what we might call (for lack of a better word) its conative dimension, for loving another involves commitment to the others wellbeing and thus taking actions to promote it, often actions that seem to go against the lovers interests. If I merely believe that your good is thereby also my good but I do nothing to promote your good when I am able to do so, it is hard to take seriously my claim that I love you. The upshot and real point of proper musical education, then, is that the guardians love the city. Where for Thrasymachus there is a clear gap between what is good for me as a ruler and what is good for the city, Socratic love for the city closes this gap. That a certain course of action might benefit me as a ruler at the expense of the city gets no traction if I have been properly educated; there just is not any space for such considerations to have any pull. The properly educated ruler would be baffled at the thought that they could gain from selling out the city, since the citys good is their good, just as no amount of money would induce a good parent to sell their child into sex slavery. As we will see momentarily, the citys founders must find ways to test the would-be guardians to discover which of them cannot be induced to give up their love of the city; they must make sure that neither compulsion nor magic spells will get them to discard or forget their belief that they must do what is best for the city (3.412e). Physical Educationand Food (3.403c405a) Plato says significantly less about physical education, the other prong of the would-be guardians education. Given that the Greek word here is (gumnastik, from which we get the English word gymnastics), we might expect a discussion of various kinds of exercises, but detailed supervision of the body (3.403d) is not really necessary, Socrates thinks, as a well-cared-for soul will be able to figure out what is appropriate for the body. He will return to the topic of physical education, especially as it concerns soldiering, in Book V. But here Socrates does offer a of bit detail where food is concerned, with examples drawn from Homer. The soldier-guardians will eat roasted but not boiled meats, presumably because this requires less 84 Platos Republic: An Introduction equipment to be lugged around. There will be no fish, which as we noted above is a luxury item, no sweet desserts, and no Syracusan or Sicilian delicacies ( [opson]) (3.404d)though this time Glaucon raises no objection. The guardians lifestyle should be simple, both musically and physically. Simple music conduces to personal in the soul and simple food conduces to bodily health. Symptoms of Poorly Educated Cities: Too Many Lawyers and Doctors (3.405a408c) Given how frequently one hears jokes about lawyers and complaints that American society is overly litigious (Googles fascinating Ngram Viewer shows a twofold increase in the use of the word litigious in American English in the last half of the twentieth century), it is likely that many readers will agree with Socrates that an overabundance of lawyers is a symptom of something amiss, bemoaning those who take pride in being clever at [] exploiting every loophole and trick to [ensure that their clients] escape conviction (3.405c). Fewer, I suspect, are likely to bemoan the presence of doctors, as Socrates does. At least as regards illness resulting from idleness and dubious dietary choices, we may concede that he has a point. But many readers will find what Socrates says about disease and disability shocking and indeed morally abhorrent. His remarks about those who are chronically, incurably ill are apt to make one shudder: as for the ones whose bodies are naturally unhealthy or whose souls are incurably evil [] let the former die of their own accord and put the latter to death (3.410a). One reason Socrates attitude can seem horrifyingly wrongheaded is that it seems driven by the Specialization Principle and his communitymindedness: everyone in a well-regulated city has his own work to do and [] no one has the leisure to be ill and under treatment all his life (3.406c). Since the chronically ill cannot contribute to the city, the argument seems to go, caring for them would just be a drain on resources. Many readers will insist that individuals have a value that transcends their usefulness or instrumental worth, and that treating them as dispensable cogs in a great machine is profoundly immoral, as it fails to recognize and respect their inherent dignity. Here we seem to find the starkest of clashes between individualism and communitarianism. Without seeking to defend Blueprints for a Platonic Utopia 85 Socrates attitude, it is worth noting that this is only half the story, for he also appeals to the perspective of the diseased individual: such a person would be of no profit either to himself or to the city (3.407e); his life is of no profit to him if he does not do his work (3.407a). While this might blunt the sharp edges of Socrates view, it does so in a way that many people, informed by contemporary thinking on disability or by their own life experiences, will find offensive and profoundly mistaken. For it seems to take as its guide not the perspective of those who are chronically ill or disabled but rather the perspective of healthy people imagining how they would react to permanent disability. Empirical research suggests that the perhaps commonsensical assumption that disabilities make the lives of the disabled significantly if not disastrously worse is mistaken, and many readers will themselves have lives well worth living or will have friends and family members whose lives are well worth living despite their physical and cognitive limitations. We might share some of Socrates wariness about excessive care [and attention] to the body (3.407b), being aware, as he is not, of the corrosive dangers of cultural norms of physical perfection, without sharing his attitude toward the disabled. And many will regard Socrates attitude as not only morally abhorrent, but philosophically suspect, as well. On the medical model of disability, a disability is thought of as an abnormality, such as an inability to walk that in itself significantly impairs its possessors chances for a happy, flourishing life. But the social model of disability, which is now the standard view in the field of disability studies, challenges the medical model. It distinguishes impairments from disabilities, regarding the inability to walk, for example, as atypical rather than abnormal. It is an impairment, but it is a disability only in a society that is inhospitable to and stigmatizes those who cannot walk. On the social model, being disabled is largely a social fact, turning on the ways in which a society is structured with respect to various impairments. While it might seem obvious that deafness, for example, is a disability, many regard it instead as a difference, and treasure it as part of their identity. This brief discussion is not meant to suggest that the social model is correct, but rather that thinking about disability has advanced significantly since Socrates time, and the medical model he assumes to be obviously correct has been called into serious doubt in recent decades. 86 Platos Republic: An Introduction Harmony between Musical and Physical Education (3.410a412b) As we noted above, Socrates initially said that musical education treats the soul while physical education treats the body (2.376e) but towards the end of Book III he corrects himself, holding that both are chiefly for the sake of the soul (3.410c). And here he hints at the distinction he will make in Book IV between the parts of the soul, suggesting that physical training aims at properly arousing the spirited part of ones nature while musical education tends the philosophical part (3.410d). His overriding concern is that the two parts be brought into harmony or balance. Remember that guardians must be both gentle and highspirited, traits that are typically not found together and that are in tension when they are. Too much gumnastik and one ends up savage and harsh rather than spirited; too much mousik results in softness rather than gentleness. As noted earlier, the Republic is written in the decades following Athens defeat by Sparta in the nearly three-decadeslong Peloponnesian War. It is not a stretch to see Plato here trying to find a balance of the best of the Spartan and Athenian temperaments while avoiding their excesses. Towards the end of Book III, the artistic culture of the ideal city has been morally purified, lest citizens be harmed by being exposed to images of evil (3.401b), like cows grazing in a meadow of bad grass (3.401c). The potential guardians are subjected from youth on to a series of tests designed to see whether their belief[s] that they just do what is best for the city (3.412e) can survive the blandishments of pleasure, the pressures of compulsion, and the effects of time and rhetoric. Here and elsewhere in Book III Socrates is concerned with changes that escape notice. A potential guardian who can be persuaded by a sophist, such as Thrasymachus, will not pass muster, since clever rhetoric can take away their opinions without their realizing it (3.413b). After describing the tests employed, Socrates distinguishes complete guardians from the auxiliaries, resulting in a city with three classes: guardians or rulers, auxiliaries, and craftspeople. As will become clear, these are not socioeconomic classes but rather political classes, distinguished not by wealth but by political authority. The rulers and their helpers that is, the guardians and the auxiliarieslive a spare, Blueprints for a Platonic Utopia 87 communal lifestyle, owning no private property, and living together in military-style barracks, as befits warrior athletes (3.416e). Though it might be tempting to think that those who pass these exacting tests are guardians while those who do not are merely auxiliaries, this clearly will not do: the auxiliaries must also be guardians of this conviction [] that they must do what is best for the city (3.412e). The difference is age and experience: the auxiliaries are young people (3.414b), while presumably the guardians, like good judges, are older and have more experience. A good judge, Socrates thinks, has learned late in life what injustice is like and who has become aware of it not as something at home in his soul, but as something alien and present in others, someone who, after a long time, has recognized that injustice is bad by nature, not from his own experience of it, but through knowledge (3.409b). We will soon see that a crucial difference between auxiliaries and guardians is that the auxiliaries have unshakable and true beliefs about what is best for the city, the guardians have something even firmer: they have knowledge of what is best for the city The Noble Falsehood (3.414b417b) The structure of the ideal city now set, Socrates offers a three-part foundational myth for the ideal city, which he calls the noble falsehood (3.414b). He imagines telling the first-generation citizens of the nowcompleted city that they are born from the earth, which is their mother. They literally are of the soilthe soil of this place. This presumably will make them eager to defend their city-state, as one would be eager to defend ones mother. The second part of the myth follows from the first: since they are born of the same soil, they are all related, all brothers and sisters. Thinking of ones fellow citizens as family, he thinks, will bind the city together as one, making the citizens love each other as family members ideally do. For many of us, family bonds transcend reasons in an interesting and important way: whether ones siblings merit ones love seems beside the point; the basis of family affection is the bare fact of being related: that someone is your brother or sister itself provides reasons for action. Some philosophers are suspicious of the kind of loyalty that is grounded in pure relations rather than reasons, since it can lead to immoral or illegal actions, as many a Law & Order episode 88 Platos Republic: An Introduction will attest. While we might expect Socrates to explore and question such loyalty, instead he exploits it, finding unifying power in familial love. Readers will remember that among the restrictions on stories about the gods is that no stories about gods hating or fighting each other will be allowed, since we want the guardians of our city to think that it is shameful to be easily provoked into hating one another (2.378b), which is impious (2.378c). The last element of the Noble Falsehood is the famous Myth of the Metals: the god who made you mixed some gold into those who are adequately equipped to rule [] He put silver in those who are auxiliaries and iron and bronze in the farmers and other craftsmen (3.415a). So each class of the city is distinguished by the kind of metal that dominates the souls of its members. This is one of the most interesting as well as objectionable parts of the Republic. Its interest, I think, is its indicating Platos awareness of the importance of myth in public life, especially myths of origin. Though humans are rational, we are not entirely rational. Earlier, Socrates appealed to the love the guardians have for the city as the glue binding them to it, although it is a love more cognitive than affective. And we just saw that the primary purpose of the second part of the Noble Falsehood is to cause the citizens to love each other. In having Socrates offer the Noble Falsehood, Plato is acknowledging the power and importance of myth, not just to human self-understanding but to the formation of a people of a nation or, here, a city-state. What the Myth of the Metals does is to provide a narrative understanding and mythic justification of the ideal citys three-part and decidedly non-egalitarian structure. The guardians most important task, Socrates says, is to guard against the mixture of metals in the souls of the next generation (3.415b), for the city will be ruined if it ever has an iron or bronze guardian (3.415c). Oddly, there is no claim that letting the silver-souled auxiliaries rule would have this destructive power. It is clear that Socrates must think of the Noble Falsehood as a merely verbal falsehood, one of those useful falsehoods (3.414b) mentioned at the end of Book II, rather than a true or genuine falsehood, which is a falsehood about the most important things (2.382a). Thrasymachus belief that the unjust life is the happier life would be a true falsehood, on Socrates view. It is not a true lie, since lying requires intentional Blueprints for a Platonic Utopia 89 deception, trying to get others to belief what you regard as false, and there is nothing to suggest that Thrasymachus does not sincerely hold the view he espouses. But, on Socrates view, anyway, it is a true falsehood. It is not just factually false, but morally false and profoundly damaging to someone who believes it, since someone who lives their life by it cannot be happy (a claim he will try to prove in the last third of the Republic). Like the allowable stories about the gods and heroes, the Noble Falsehood is factually falsethe citizens are not in fact born from the soil and are not actually distinguished by the kinds of metals in their souls. But its message, Socrates thinks, is deeply true. This is where the Noble Falsehood is apt to seem most objectionable, for the profound claim it expresses, cloaked in mythic garb, is that human beings are not created equal. The guardians are simply more valuable than the craftspeople, Socrates holds, in the same way that the sexist thinks that men are just more valuable than women and the racist thinks that white people are just more valuable, possess more intrinsic worth, than non-whites. Anyone who subscribes to the fundamental moral and political equality of human beings will have to regard Socrates Noble Falsehood as not merely a verbal falsehood but rather a true falsehood, with profoundly harmful consequences to those who believe it. If it is a compelling myth, a craftsperson will see nothing amiss in not having a voice in how the polis is governed; it is just not their place. Much of the power of myth is ideological: making what is contingent and constructed seem natural and necessary. In a memorable passage from My Bondage and My Freedom, Frederick Douglass recalls having been taught from the pulpit at St. Michaels, the duty of obedience to our masters; to recognize God as the author of our enslavement; to regard running away an offense, alike against God and man; to deem our enslavement a merciful and beneficial arrangement [] to consider our hard hands and dark color as Gods mark of displeasure, and as pointing us out as the proper objects of slavery.1 1 Frederick Douglass, Autobiographies: Narrative of the Life of Frederick Douglass, an American Slave/ My Bondage and My Freedom/ Life and Times of Frederick Douglass, ed. by Henry Louis Gates (New York: Library of America: 1994), p. 306. 90 Platos Republic: An Introduction Douglass, being Douglass, is able to pierce the veil of racist ideology in which slavery is clothed. He recognizes that, the Bible (or supposedly authoritative interpretations of it) notwithstanding, he is not a proper object of slavery: no one is. But such is the power of ideology and myth to make a contingent institution like slavery seem to be metaphysically necessary and ordained by God. I suspect that most readers will agree that the Noble Falsehood is in fact a true falsehood, rather than the beneficial verbal falsehood Socrates takes it to be, since it denies the fundamental equality of all persons. I should stress that to believe in human equality is not to believe that all humans are equally able to do calculus, hit a curveball, nurture their children, etc. It is not a belief in factual equality. It is a belief in moral equality, in the equal dignity of all persons. There are many places where the Republic butts up against deeply held but often implicit and perhaps unjustified beliefs many of us have. And though there are times when we are likely to arch our eyebrows and wonder if Plato is not really onto something in thinking as he does, I do not think this is one of those times. Some Suggestions for Further Reading Readers interested in philosophical issues raised by music will find Peter Kivy, Introduction to a Philosophy of Music (Oxford: Clarendon Press, 2002) well worth their time. Less is known about ancient Greek music than one might expect, but interested readers should see M. L. West, Ancient Greek Music (Oxford: Clarendon Press, 1994). Readers interested in Jeffersons Bible can find it at the Smithsonian Institutes webpage: http://americanhistory.si.edu/jeffersonbible/. Readers interested in issues around disability will find Andrew Solomon, Far From the Tree: Parents, Children, and the Search for Identity (New York: Scribner, 2012), especially its first chapter, well worth reading. For a clear-headed, clearly written contemporary philosophical take on disability, see Elizabeth Barnes, The Minority Body: A Theory of Disability (New York: Oxford University Press, 2016). Blueprints for a Platonic Utopia 91 Readers interested in exploring conceptual and ethical issues about deception and lying might start with Sissela Bok, Lying: Moral Choice in Public and Private Life (New York: Vintage Books, 1999). Josef Abel, Socrates Teaching his Disciples (1807). Photograph by Jarash (2015), Wikimedia, Public Domain, https://commons.wikimedia.org/ wiki/File:Josef_Abel_1807_Socrates_teaching_his_disciples.jpg 5. Starting to Answer the First Question: The Political Virtues, Book IV In Book IV Socrates answers the Republics first question, What is justice? Keeping to the plan devised in Book II, he first tells us what political justicejustice in the polis or city-stateis and then, arguing that the ideal polis and the human soul (psuch) share the same threepart structure, he applies his definition of political justice to the psyche, arriving at his definition of personal justice. His definition is interesting in many ways, not least of which is its accounting for justice not as a matter of outward behavior, as Cephalus and Polemarchus definitions did, but rather as an inward matter of psychic harmony. Happiness: Parts and Wholes, Individuals and Communities (4.419a421c) Book IV begins with Adeimantus jumping back into the conversation with a concern that brings to the fore the tension between individualism and communitarianism. He worries that the guardians and auxiliaries will not be especially happy, given the lifestyles Socrates described at the close of Book III: communal living, no privacy, not much money, etc. The city really belongs to them, Adeimantus says, yet they derive no good from it since they lack the things that are thought to belong to Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.05 94 Platos Republic: An Introduction people who are blessedly happy (4.419a). This is certainly a plausible view about what the best kind of life is like. The Greek verb translated as thought is (nomizetai), which is cognate with (nomos: custom or law), and thus indicates what is thought or deemed or customarily taken to be the best lifenot necessarily what actually is the best life. Plato has Socrates give a twofold response to Adeimantus. First, he suggests that far from being unhappy, the guardians may well be the happiest group in the ideal polis. They are performing the task or function for which they are best suited, after all, and if they are performing it well, they are probably delighting in it. It is another reminder that while the good of the community is Socrates primary concern, it is not his only concern. Socrates then reminds Adeimantus of the plan they have adopted, to investigate the nature of personal justice and its connection to personal happiness by discovering the nature of political justice and its connection to happiness. His focus, then, is on political happiness, on making the whole city happy (4.420c); he does not aim to make any one group outstandingly happy, but to make the whole city so (4.420b). Even though he seems to be doubling down on the holistic or communitarian ethos that is regularly contrasted with the individualism which many readers will find intuitively more attractive, his communitarianism here is largely methodological, a useful device to get to his ultimate concern, which is individual happiness. In Book V he will suggest that individual wellbeing depends in no small way on whether the polis one lives in is just, which suggests a more modest community-first ethos than he has been espousing heretofore. The Ideal City: Finishing Touches (4.421c427d) After giving a warning about the damage economic inequality can wreak in a citya theme to which he will return in Book VIIISocrates reminds Adeimantus of the importance of the guardians preserving the educational system as they have received it, lest it be corrupted by seemingly minor and innocuous changes. Many readers will have witnessed versions of such cultural conservatism in their lifetimes, for example, panicked responses to the Starting to Answer the First Question 95 threats posed by jazz, Elvis, the Beatles, and rap music. But lest Plato seem like just another cranky old fuddy-duddy bemoaning music he did not grow up with, we should remember that the ideal citys music was chosen intentionally and with great care, since it is meant to cultivate traits of character necessary to the citys thriving. The worry is that lawlessness easily creeps in [] unnoticed (4.424d), so, given how malleable young people are (a fact of human nature that is highly relevant to the educational system developed in Books II and III) it is important that music and culture generally provide sustenance to young souls. Children will absorb lawfulness or lawlessnessPlato mentions no neutral third optionfrom the games they play and the songs they sing and hear, so it is vital that the healthy system be preserved. Changes of mode and meter can seem trivial and morally neutral, but they are not, on Platos moral-aesthetic conception of character development. Even if we do not share Platos worry that changing to a new form of music [] threatens the whole system (4.424c), keeping in mind his beliefs in the malleability of young minds and the inseparability of morality and aesthetics should render his worry at least less curmudgeonly. Though there are several other things worth discussing in this part of Book IV, I will mention just one, what we might call Platos legislative minimalism. It is foolish, Socrates says, to think that legislation can overcome failures of education. Though some of his examples are trivialregulating hairstyles and clothesothers are not: how the young treat the old and how they care for their parents, for example. This brief stretch of the Republic might seem little more than harrumphing about kids today, but Plato is doing more than mere griping here. He might not agree with the details of Ed Toms diagnosis in Cormac McCarthys No Country for Old MenIt starts when you begin to overlook bad manners. Any time you quit hearin Sir and Mam the end is pretty much in sight. I told her, I said: It reaches into ever strata.1but in principle they seem to be of one mind. Communities are held together by more than rules and laws; they are held together by shared values and affections. Education in Platos broad sense is primarily character education, after all, and there is something to his point that legislation cannot repair defective character 1 Cormac McCarthy, No Country for Old Men (New York: Vintage Books, 2006), p. 304. Spelling, syntax, and italics as in original. 96 Platos Republic: An Introduction education. Still, we might worry that his view ignores the expressive function of lawthe laws power to say something about the shared norms and values that bind a community together. If, in addition to governing behavior, the law can also shape attitudes and beliefs, then it may have a contribution to make to character education, if only an ancillary one. In my home state of Wisconsin, adultery is a crimea felony, in fact. Prosecutions are extremely rarethere have been none in the last thirty yearsbut presumably that is not because there have been so few violations of Wisconsin Statute 944.16. I know of no empirical studies of this laws efficacy in reducing adultery, but it seems unlikely that potential adulterers would be deterred by it, especially given its non-enforcement. But even if there is no direct causal link between criminalizing adultery and reducing extramarital adventuring, its criminalization may yet serve an important function: expressing the citizenrys collective disapproval of adultery. If the law plays this expressive role, striking the adultery statute from the books might seem to signal, if not the communitys approval of adultery, at least its non-disapproval, and it is not implausible that this would have negative behavioral consequences, by changing attitudes and feelings about the importance of marital fidelity, promise-keeping, etc. So there may be a dimension to the law that Plato is missing here. On the other hand, a laws remaining on the books because of its expressive function might cultivate the sort of cynicism and hypocrisy Adeimantus complains about in Book II: many citizens make a great show of the importance of the values just mentioned, because it is important to seem just, but in practice their conduct suggests a preference for being unjust. The Political Virtues (4.427d434d) Now that the ideal city is complete, it is time to look for justice in it. But before we do that, I bring up a seemingly minor point that, as is so often the case with Plato, is surprisingly deep upon examination, carrying more philosophical weight than initial appearances suggest. In announcing the completion of the ideal city, which paves the way for the inquiry into the nature of justice, Socrates says to Adeimantus, your city might now be said to be established (4.427d). This seems Starting to Answer the First Question 97 innocuous enough, but up to this point, Socrates possessive pronoun of choice has been the first-person plural: he speaks of our city and our citizens (2.370d, 2.371e, 2.373b, 2.378b, 3.387e, 3.394d, 3.397d). At the corresponding point in Book II, at the completion of the first city, Socrates says, Well, Adeimantus, has our city grown to completeness, then? (2.371e; emphasis added) Why the shift here from our city to your city? Perhaps it is merely stylistic variation on Platos part. After all, within just a few lines Socrates shifts back to our city (4.427e), and then it is soon back again to your city (4.431c). I suspect that the shift in pronouns is Platos way of reminding us that Socrates, despite being the chief theoretical architect of the just-completed ideal city, still regards the first city, the rustic utopia rejected by Glaucon as a city for pigs (2.372d), as the true city [] the healthy one (2.372e). Perhaps Plato hopes his readers will pick up on Socrates ambivalence and reflect further on his allegiance to his rustic utopia. That city, which has been all but forgotten by this point in the Republic, was without guardians and auxiliaries and indeed without classes of any kind. The just-completed city is not only structured by political classes but in fact, we will soon see, has the same structure as the human soul. This is a perfect place to remind attentive readers of the second-best nature of the ideal city, if only to make us think through how seriously to take Socrates attitude toward it. So what seems a matter of mere style may turn out to be really a matter of substance, though we will not pursue so fine a point any further. Hopefully, though, this brief discussion reminds us of what a subtle work the Republic is and why it rewards repeated rereading. Cardinal Virtues If the city is well founded, Socrates argues, it will be completely good (4.427e) and thus it will not be missing any of the moral virtues. For Socrates and Plato, there are four primary virtues: courage, moderation, wisdom and justice. Aristotle had a much longer list, including friendliness, wit, generosity, and proper pride, among others. Philosophers often speak of Platos four virtues as the cardinal virtues, which suggests at a minimum that the virtues are important or paramount. But in another, stronger sense, to call a virtue a cardinal 98 Platos Republic: An Introduction virtue is to say that it is theoretically basic: there are no virtues more basic than it and any non-cardinal virtue is somehow reducible to or a version of the cardinal virtue in question. Socrates says that there are four virtues (4.428a) and that together they make the city completely good (4.427e), which suggests that these virtues are cardinal in the stronger, theoretically basic sense. To see what is at stake here, consider the attention paid earlier in the Republic to cultivating the virtue of piety by regulating stories about the godsand consider Platos having devoted an entire dialogue (the Euthyphro) to investigating the nature of piety. If piety is not a cardinal virtue, perhaps it can be subsumed under justice, since piety concerns what is owed to the gods and justice is plausibly thought of as giving to each what they are owed. Viewing piety as a requirement or form of justice would preserve the cardinality of Socrates four virtues. One problem with this view, however, is that in Book I Socrates casts doubt on defining justice in terms of what is owed, and we will soon see that the definition of justice Socrates proposes is not couched in terms of giving to each what they are owed. Another, related, worry is that what goes for piety can also go for the other virtues. If courage, for example, can be thought of as what soldiers owe the city, then like piety courage is not itself a distinct virtue but instead a kind of justice. So by seeking to preserve the cardinality of the four cardinal virtues we end up destroying their cardinality. This concern about piety is in a sense internal to Platos moral thinking and to the account of virtue he is offering here: he seems committed to pietys being a genuine, stand-alone virtue and yet he excludes it from his official list. A different kind of concern is external: when looking at Platos list we might think he is excluding some traits we take to be virtues. Many readers will think of kindness and generosity, for example, as virtues of character, and thus think Platos list is mistaken not because of an internal inconsistency or tension but because it fails to include traits that belong on the list. When thinking about the attitudes Socrates expresses toward the disabled in Book III, many readers will think that the virtue of compassion is in short supply in his ideal city. It would be difficult to subsume generosity under justice, since generosity is at least in part a matter of giving which goes beyond what is owed. Starting to Answer the First Question 99 Yet another worry concerns the argument Socrates gives for the complete goodness of the ideal city: P1 If our city has been correctly founded, it is completely good. (4.427e) P2 Our city has been correctly founded. C Therefore, our city is completely good. While we might question why correctness must imply completeness, P1 seems plausible. But many readers, noting the absence of individual liberty and equal political rights in the ideal city, will have grave doubts about P2. Socrates more community-minded interlocutors raise no such objections, but as thoughtful readers we will want to engage in philosophical dialogue with our author by thinking through the issues for ourselves, in both senses of for ourselves. We want to think about these issues independently, not merely relying on what Plato or Socrates or whoever has to say. And we want to think about what Socrates claims mean to us. As he reminds his readers at various points, Socrates method depends upon his interlocutors saying what [they] really think (1.349a). Good philosophical reading often requires adopting anothers point of view, examining whether the claims an author makes from within that point of view are consistent with it. But good philosophical reading also requires scrutinizing that point of view itself, not just for its internal consistency but also for its substantive correctness. Of course, there is a danger here of taking our own points of view as sacrosanct and beyond criticism and rejecting points of view at odds with them. But one of the values of reading a book like the Republic, which expresses perspectives very different from our own, is that they can prod us to think through our deeplyheld but not always carefully, critically scrutinized beliefs. As usual, there is more to be said here and by no means am I suggesting that Plato has no plausible responses to these worries. But in questioning the adequacy of his claim about how many virtues there are we honor him by doing the thing he most wants of us: to think philosophically and critically. 100 Platos Republic: An Introduction Wisdom (4.428a429a) The first virtue discovered in the city, wisdom ( [sophia]), is the virtue of a particular class: the guardian-rulers. Wisdom is often thought of as an intellectual virtue, rather than a character virtue, as it is a kind of knowledge. Aristotle distinguished the intellectual and character virtues (although he ultimately thought that some of them were mutually dependent). While this is not a distinction Plato explicitly makes, it is a helpful one, both in itself and for the light it will shed in Book VII of the Republic, when Plato is busy distinguishing philosophers from non-philosophers. Wisdom is a kind of knowledge, Socrates thinks, but not just any old kind of knowledge and certainly not the kind of knowledge that craftspeople possess. Nor is it the kind of abstract, theoretical knowledge a mathematician might possess. It is more general than the craftspersons know-how and more practical than the mathematicians know-that. It is knowledge of what is best for the city as a whole (4.428c). Although many readers are leery of Socrates holism and communitarianism, here they seem unproblematic: wisdom is knowledge of what is best for the city as a whole, not what is best for any particular group of citizens. If the city is to function well, it must be unified, and it can only be unified if its rulers aim at the good of the whole, rather than at what is good for a particular part of it at the expense of the whole. Socrates has already implied that good rulers will strive to minimize economic inequality, given its dis-integrating effects. Some economic inequality is to be expected and may well be beneficial, but too much leads to there not being a city [] [but] two cities at war with one another, that of the poor and that of the rich (4.422e [italics in the original]). Just as the ideal citys founders aimed not to make any one group outstandingly happy but to make the whole so, as far as possible (4.420b), its rulers must aim at the good of the city as a whole. It should make sense that this is the virtue distinctive of the guardians, if we remember the earlier account of a virtue as what enables its possessor to perform its function well. Since the function of the rulers isunsurprisinglyto rule, they can rule well only if they possess wisdom. A ruler who makes only lucky guesses, or even educated guesses, about what is best for the city is less likely to rule Starting to Answer the First Question 101 well than a ruler who knows what is best for the city. Now of course we can agree that rulers require wisdom to rule well without agreeing with Socrates conception of it or with his belief that only a few citizens are capable of it. One might be skeptical that knowledge about what is best for a city-state or country is really possible, settling instead for experience-grounded beliefs. And one might think wisdom is at least in principle within the grasp of ordinary citizens. We have already seen, and will see in more detail in Books VIII and IX, that Socrates is no fan of democracypresumably because he is skeptical that ordinary citizens are capable of the sort of knowledge needed to rule well. Courage (4.429a430c) Courage, like wisdom, is also a virtue distinctive of a particular class: the soldiering auxiliaries. It becomes clear that the guardians, who emerge from the auxiliaries, will also possess courage, but their distinctive (rather than sole) virtue is wisdom, not courage. As above, their possessing courage makes sense when we remember that the auxiliaries function is to protect the city, which they can do well only if they possess courage. A surprising way in which courage is similar to wisdom is that courage, at least as Socrates characterizes it, is at root a cognitive affair: it is th[e] power to preserve through everything the correct and law-inculcated belief about what is to be feared and what is not (4.430b [emphasis added]). Attentive readers will have noticed that the wisdom the guardians possess is a kind of knowledge, but the auxiliaries courage is a matter of belief, not knowledge. Making clear how knowledge and belief differ will be a central focus of Books V, VI, and VII. It might be helpful to bring the JTB (justified true belief) conception of knowledge into play again (reminding ourselves that it is not Platos view but rather a heuristic to help us make sense of some features of the Republic). The auxiliaries believe that certain things are worse than deathslavery and dishonor, for examplebut the guardians know why these things are worse than death: they have, in addition to a true belief, a justification for their true belief. While the auxiliaries beliefs lack the intellectual backing the guardians possess, this in no way prevents their holding it firmly and unshakably. Their belief that there are fates worse than death must be dyed-in-the-wool, in Socrates memorable metaphor: dyed in so 102 Platos Republic: An Introduction deeply that the color is fastno amount of washing [] can remove it (4.429b). If the Spartan soldiers holding the pass at Thermopylae against Persian invadersan event that, until the film The 300, was the province of classicists and history nerdsvalued their own lives over the good of the community, they would have thrown down their weapons and run for safety. The opening pages of Book III, attentive readers will remember, were rife with constraints on stories and poetry designed to cultivate courage. Any would-be auxiliary who believes that their death would be the worst thing that could happen believes a true falsehood, a belief that is radically false and distorts an important dimension of reality. The auxiliaries education, both poetic and physical, is meant to cultivate the virtue of courage. We should note a subtle but important refinement Socrates makes to his definition of courage. He first describes courage as the auxiliaries power to preserve through everything its belief about what things are to be feared (4.429b), but he quickly adds a qualifier: courage is preservation of the belief that has been inculcated by the law through education about what things and sorts of things are to be feared (4.429c [emphasis added]), a qualification he repeats a page later: the correct and law-inculcated belief (4.430b). He is making a distinction between what Aristotle will later call natural virtue and virtue proper. Some people and indeed many animals seem by nature courageous, born with correct beliefs about what is properly feared and with the power to preserve those beliefs in the face of danger. But unless these beliefs are the product of education, what is present is not courage but something else (4.430b). Socrates does not elaborate, but presumably he thinks this because proper courages natural analog may misfire without the guidance of reason and education. We have already seen that too much physical education and not enough musical education results in a persons becoming hard and harsh (3.410d) rather than courageous. Moderation (4.430d432b) Unlike courage and wisdom, moderation is not distinctive of any particular class in the city; instead, moderation spreads throughout the whole (4.432a). Socrates starts with the commonsense connection between moderation (also called temperance) and self-control. If you Starting to Answer the First Question 103 decline and I insist on a third slice of cheesecake, you seem to have and I seem to lack the virtue of moderation. But explaining this in terms of self-control is puzzling, Socrates thinks, since what does the controlling and what is controlled is the very same thing. The puzzle is solved when we realize that our souls have better and worse parts, with the better part comprising our capacities for reason and choice and the worse part our appetite and desires. In the self-controlled person, the naturally better part is in control of the naturally worse (4.431a), so they decline that third slice of cheesecake while I do not. There is something problematic about Socrates procedure here. The plan is to figure out the nature of the political virtues in order to discover the nature of the personal virtues. But here he is appealing to the structure of the soul or person in trying to understand the nature of the political virtue of moderation, so he is building into the polis the psychic structure he will soon claim to find there. As a grad school professor once wrote in the margins of a paper of mine, if you are going to try to pull the rabbit out of the hat, it is best if you are not seen putting it in. But perhaps there is no big problem here. After all, Socrates is simply appealing to an ordinary belief about moderation as a kind of selfcontrol; he is not importing any high-level psychological theory, and he may well have been able to arrive at his conclusionthat something in which the better rules the worse is properly called moderate and selfcontrolled (4.431b)without the appeal to commonsense psychology. The ideal polis is self-controlled and thus moderate, Socrates thinks, because it is ruled by the guardians, who are the best part of the polis. But there is more to it than that. A city in which the guardians only tenuously hold power over the rebellious craftspeople is not moderate, nor would Socrates think it is, for it is lacking the harmony distinctive of true self-control. In a moderate or self-controlled polis, the three classes all sing the same song together (4.432a): there is agreement between the naturally worse and the naturally better as to which of the two is to rule (4.432a). As with the wisdom and courage, Socrates plays up the cognitive nature of this virtue: ruler and ruled [] share the same belief about who should rule (4.431d [italics added]). They are in agreement, not in the way in which a good drawing or measurement agrees with its object or in the way in which some food agrees with my finicky stomach but 104 Platos Republic: An Introduction other food does not, but in the way that only rational creatures can be: consent. We should tread carefully here, however, for the idea of consent can be misleading. Socrates is not offering the modern, liberal view that the legitimacy of a government turns on the consent of the governed. The consent Socrates has in mind is a symptom of good government, not a condition of its legitimacy. Presumably, in a well-governed city, the craftspeople consent to being governed by the guardians because things are going well for them economically; they are happy with the arrangement and are happy to be left alone to their cobbling, baking, doctoring, etc., and their family lives. The entitlement of the guardians to rule depends not on the consent of those they govern but on their possessing the relevant virtue, wisdom. A word or two about the spread out nature of moderation is in order. Unlike wisdom and courage, which are what we might call particular virtues, which are virtues distinctive of particular classes, moderation is a holistic virtue, a virtue of the whole city, not of any of its particular classes. This is a subtle point, easily misunderstood. Although a city is wise because its rulers are wise and brave because its auxiliaries are brave, Plato is not saying that the city is moderate because every class is moderate. Moderation does not work that way. By way of analogy, think of a basket containing red balls, green balls, and yellow balls. The collection of balls has a property which none of its members has: the property of being multi-colored. The collection is multi-colored because of the colors of the individual balls: if the basket contained only green balls, the collection would not exhibit the property of being multicolored. But none of the individual balls in the basket is multi-colored: each is either red or green or yellow. (Of course, nothing prevents individual balls from being multi-colored: a particular ball might be red, green, and yellowbut none of the balls in our example has this property.) So the collections having this property depends upon the members having certain propertiesbut it is the collection, and not its members, that has the property of being multi-colored. Being multicolored, in this example, is a holistic property, depending on the nature of the individuals but not reducible or equivalent to them. The political virtue of moderation, as Socrates conceives of it, is the same kind of holistic property, belonging to the whole and not to the parts. It is not the case that the city is moderate because each class is Starting to Answer the First Question 105 moderate; rather, the city is moderate because the different classes agree about who should rule, just as the basket of balls is multi-colored even though none of the balls are. Socrates talk of better and worse parts may be easier to hear when the parts in question are parts of the soul rather than the city. Thinking of the guardians as naturally better than the craftspeople has a dissonant ring to egalitarian ears. As we noted when discussing the Noble Falsehood, the kind of equality that most readers will insist on (and which Plato has Socrates denying) is not factual equality. Some people can run or swim faster than others; some people are better at knitting than others; some people are better at differential equations than others. What is at issue is political equality, the belief that all citizens have equal rights to participating in the political life of their communities. We will see in the next chapter that Socrates expresses the view that being a woman does not in itself disqualify a person from being a guardian. But he certainly does not think that all women, or all men, are capable of being guardians, since so very few of us are capable of acquiring the requisite virtue, wisdom. We will return to this topic in the next chapter and then again when discussing Platos attitudes toward democracy in Chapter 12, so for now the egalitarians among us should merely note our disagreement with Plato. But we should also be thinking of how we might go about trying to convince him, drawing on premises he himself would accept, that he is mistaken to reject political equality. It is not an easy task. But, as I have said before, one of the great benefits of carefully reading the Republic is that doing so can lead us to wrestle with difficult tasks like this, to question and defend propositions that seem self-evident to us but do not so appear to others. Justice (4.432b434d) Since three of the four cardinal virtues have been identified, Socrates thinks that justice must be whatever is left. Justice: its what is left over does not exactly inspire confidence, either as a bumper-sticker or a philosophical methodology. But Socrates point is that the answer to the Republics first question is staring them in the face, so to speak. They have been talking about it without even knowing it, he thinks, because 106 Platos Republic: An Introduction justice is based on, and indeed seems to be a moralized version of the Specialization Principle: justice, he says, is doing ones own work, and not meddling with what is not ones own (4.433a). Although it is initially stated in terms of individual behavior, justice as a virtue of the polis is really a matter of each class doing its work: the craftspeople produce and exchange goods, the auxiliaries protect the city, and the guardians govern it. If this is indeed what justice is, Socrates earlier insistence that the guardians most important task is to protect against the mixing of the metals grows in importance. If their task is to ensure justice and prevent its opposite, then they must prevent the craftspeople from ruling, since, the Noble Falsehood informed us, the city will be ruined if it ever has an iron or a bronze guardian (3.415c). When cobblers bake and bakers cobble, the city will have suboptimal bread and sandals (and not enough of them), since this violates the Specialization Principle, which requires specialization as a way of producing more plentiful and better-quality goods (2.370c). But occupation-switching is disastrous, and not merely suboptimal, when bakers and guardians switch roles. A baking guardian who lacks the bakers skill will produce bread that is not very good, but a ruling baker who lacks the guardians wisdom will produce disaster, on Socrates view. Justice as non-meddling has intriguing parallels in Confucius Analects. When asked about good governing, Confucius replies, The ruler must rule, the minister minister, the father father, and the son son (12.11). Underlying Confucius somewhat odd way of making his point is that roles are not merely descriptive but rather normative, providing rules and norms of conduct. (This echoes the discussion of the precise sense of craft-terms such as ruler back in Book I.) A widely heard complaint about contemporary American parenting is that too many parents seek to be their childrens friend (searching Google or Yahoo for be a parent not a friend, for example, yields millions of hits). But even without investigating the complaints merits, we see its point, which is both a Platonic and Confucian one. We each inhabit many roles: citizen, friend, neighbor, mother, cousin, customer, boss, etc., and it may not always be clear which role is appropriate in a given situation. To a great degree, practical wisdom is a matter of seeing which role is appropriate in the circumstances so one can then act accordingly. And of course it Starting to Answer the First Question 107 is not always clear what the role requires, even when one determines which role is called for. It may be that in interacting with a particular employee on a particular day, being a friend rather than a boss is what is called for. But it may be that a different situation calls for just the opposite. Although this idea of the normative status of roles is plausible and intriguingindeed, Confucianism is often thought of as a kind of role ethicsmany readers will be understandably uncomfortable with the political implications of Platos role-based account of justice, rejecting the idea of assigning to a fellow citizen the rank appropriate to his nature (3.415c), for it seems an easy, morally problematic slide from here to insisting that others know their place. Role ethics is a fascinating topic, but exploring it in more depth would take us too far afield. So instead, let us briefly explore two arguments Socrates makes in support of his definition of political justice. The first argument is explicitly marked in a way that should garner our attention: Look at it this way if you want to be convinced (4.433e), Socrates says. The argument turns on the proper role of a judge, which is not surprising, given the focus on roles. The ideal citys rulers will also be judges, Socrates argues, and a judges sole aim is that no citizen should have what belongs to another or be deprived of what is his own (4.433e)because this, intuitively, is just. Therefore, Socrates concludes, the having and doing of ones own would be accepted as justice (4.434a). This seems plausible, and Glaucon finds it so. But a more critically disposed reader might question the sudden appearance of doing ones own in the conclusion, when the premises have concerned only having ones own. Socrates argument is commonsensical and intuitive because it concerns property: justice requires that I not be wrongfully deprived of my property. Is what one does properly thought of something one has? Are ones roles to be counted among ones property? Perhaps, but if being, doing, and having are distinct metaphysical categories, we should be leery of fusing them into each other. The second argument is also simple and straightforward. Since meddling and exchange between these three classesthat is, the mixing of the metalsis the greatest harm that can happen to the city and injustice is the worst thing one can do to ones city, it follows, Socrates argues, that meddling is injustice (4.434c). And if meddling is injustice, 108 Platos Republic: An Introduction it must follow that its opposite, not meddling, is justice. A reader who suspects that this argument begs the questionthat it assumes the truth of what it is trying to proveseems to be on the mark. Only someone who already accepts the proposed definition of justice would accept the arguments first premise, that meddling is the worst evil that could befall the city. And even waiving that worry, egalitarian-minded readers who are friendly to democracy are likely to think that the first premise is simply false. They are likelier to think that the hierarchical, elitist structure of Socrates ideal city is among the worst evils that can befall a political community. And sharp-minded readers will wonder whether Socrates is confusing cause and effect, thinking that even by Socrates lights the meddling itself is not the great evil but rather is the cause of the evil, which presumably is the disintegration of the city. Many such readers will be skeptical that meddling or metals-mixing will cause the great harm Socrates claims for it. In addition to these external worries about Socrates definition of justice, there is an internal worry about itthat is, a worry from within Socrates point of viewconcerning the cardinality of the cardinal virtues. Piety, the reader will remember, is treated elsewhere in the Republic (and elsewhere in Platos dialogues) as a distinct virtue in its own right. But Socrates does not count it as a cardinal virtue (or even mention it) in Book IV. Earlier I suggested that attempting to regard piety as a form of justice (and thus retaining Socrates view that there are only four moral virtues) did not pan out. Here, the concern is that justice, as Socrates describes it, and moderation are so similar that it is difficult to count them as two virtues. A city is moderate when all three classes share the same belief about who should rule (4.431de) and it is just when each class does its own work, but it is hard to see how those are really different, since each class doing its own work seems to be the embodiment of the agreement. Although making an agreement and acting on it are not the same thingas anyone who has had a contractual dispute or, to choose a homier example, anyone who has experienced a child not being willing to go to bed at the agreed-upon time, can attestthe difference here does not seem sufficient to justify viewing moderation and justice as distinct cardinal virtues. If we are tempted to insist that the difference between agreement and action is sufficient to justify claims of cardinality, we might find our position turned against Starting to Answer the First Question 109 us. After all, an opponent might argue, could not the same be said about courage? Surely a belief that x is an appropriate object of fear and acting on that belief are not the same thing, even if they are closely related. If so, there would need to be another virtue, related to but distinct from courage; and if that is the case, then Socrates is mistaken that there are four virtues (4.428a). While Socrates does not wrestle with this problem directly, his view that justice is a sort of meta-virtue might implicitly solve his problem. The prefix meta- suggests a higher-level or higher-order aboutness. Metacognition is cognition about cognition: thinking about thinking. Though it is often more at home in psychological contexts, there is a sense in which we are engaged in meta-cognition here: we are thinking about Platos thinking about justice. So to call justice a meta-virtue is to suggest that it is a virtue about the other virtues. Even so, there is a sense in which thinking of justice as a meta-virtue can be misleading. Cognition comes before meta-cognition: there is no thinking about thinking unless there is first some thinking to think about! But on Socrates view, justice comes before the other virtues: it is the condition of their possibility, the power that makes it possible for them to grow in the city and that preserves them when they have grown for as long as it remains there itself (4.433b). It is worth emphasizing the word power in this description (the Greek word is (dunamis), from which the English word dynamic derives). Justice is a power that enables agreement about who should rule; it is what makes it possible for there to be an agreement in the first place. Justice so conceived is not merely everyones doing his own work, but is rather the power that consists in everyones doing his own work (4.433d [emphasis added]). Similarly, courage is not merely the correct belief about what is appropriately feared, but is the power to preserve through everything [the] belief about what things are to be feared (4.429c). Earlier, I emphasized the belief at the center of courage, to draw a contrast with the knowledge that constitutes wisdom. Indeed, that is what enabled the imaginary interlocutor above to drive a wedge between belief and action. Reminding ourselves that courage is not merely a belief, but rather the power to preserve that belief through thick and thin, closes that gap. Socrates idea that justice is what makes the other virtues possible certainly makes sense for moderation, especially if we remember that 110 Platos Republic: An Introduction the shared agreement about who should rule is a symptom of a wellgoverned city, and not, as we moderns tend to think, the ultimate condition of the governments legitimacy. It seems initially to make less sense for courage and wisdom, since they are particular rather than holistic virtues (virtues distinctive of particular classes rather than of the city as a whole). Would would-be rulers and auxiliaries still possess their distinctive virtues even if justice did not prevail in the city? Those capable of ruling would still know what is best for the city as a whole even if they are not in fact ruling, and the same would seem to go for would-be auxiliaries. Indeed, just these sorts of situations arise as the ideal city begins to disintegrate, as described by Socrates in Books VIII and IX. Perhaps. But the time and attention Socrates has devoted to education in the ideal city suggests that while wisdom and courage can be defined and understood independently of justice, they cannot be manifested or made real in its absence. Much of the program of education Socrates spells out in Books II and III is devoted to educating the auxiliaries. He will return to education in Book VII, but there his focus will be on educating the guardians, sketching out a program that will ultimately enable them to grasp the nature of goodness itself, which they will need if they are to know what is best for the city as a whole and not merely have correct beliefs about this. So even if we can understand what courage and wisdom are independently of justice, we can imagine Socrates saying, those virtues will never come to be without the rigorous educational program of Books II, III, and VII, which is why it is so crucial for the guardians to defend it and resist all attempts to change it even slightly. In Book III Socrates indicates that the guardians most important task is to prevent the mixing of the metals described in the Noble Falsehood: there is nothing that they must guard better or watch more carefully than the mixture of metals in the souls of the next generation (3.415b). What he says in Book IV initially seems to conflict with this, since there he suggests that their most important task is to guard the one great thing [] education and upbringing [] [that] those in charge must cling to education [] guarding it against everything (4.423d24b). It seems that these distinct tasks cannot be the one most important task. But indeed, they really are one and the same task, since the only way to prevent the mixing of the metals is to preserve the educational system. Indeed, as we will see when Socrates describes Starting to Answer the First Question 111 the disintegration of the ideal city in Books VIII and IX, the decay begins when they have less consideration for music and poetry than they ought [ and] then they will neglect physical training (8.546d). These changes to education are quickly followed by [t]he intermixing of iron with silver and bronze with gold (8.546e). So while justice is conceptually distinct from the other cardinal virtues, they depend upon it for their coming into being in the city. Justice and the other virtues, while conceptually distinct, are not really or existentially distinct: justice is the condition of their coming into existence. Thus it is a tad misleading to call it a meta-virtue, since it is about the other virtues in a distinct way: it is the condition of their reality. It is their basistheir (arch) or foundation. Some Suggestions for Further Reading Readers interested in Platos other Socratic dialogues on the virtues will want to read the Euthyphro (on piety), the Charmides (on temperance), and the Laches (on courage), all of which are available both online and in print form. Excellent translations of all of Platos dialogues and letters can be found in Plato: Complete Works, ed. by John Cooper (Indianapolis: Hackett Publishing, 1997). Readers interested in the ethics of virtue generally and the question of the cardinal virtues in particular might start with Rosalind Hursthouse and Glenn Pettigroves excellent overview in the Stanford Encyclopedia of Philosophy: https://plato.stanford.edu/entries/ethics-virtue/. Readers interested in role ethics will find a good overview in John Ramsey, Confucian Role Ethics: A Critical Survey, Philosophy Compass, 11 (2016), 23545, https://doi.org/10.1111/phc3.12324. Readers interested in the expressive function of law might start with Cass Sunstein, Laws Expressive Function, The Good Society, 9 (1999), 5561. Bust of Athena, of the Velletri Pallas type (inlaid eyes are lost). Copy of the 2nd century CE after a votive statue of Kresilas in Athens (ca. 430420 BCE). Photograph by Aavindraa (2010), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/Category:Athena#/ media/File:Bust_Athena_Velletri_Glyptothek_Munich_213.jpg 6. The Republics First Question Answered at Last: Personal Justice, Book IV Whatever worries or quibbles we might have about Socrates definition of political justice, Glaucon finds it satisfactory: I agree. Justice is that and nothing else (4.434d). A reminder about methodology might be in order here. Back in Book I, Socrates opted for question-and-answer over speechifying as the preferred method for investigating the nature of justice. Crucial to this method is seeking agreement with each other (1.348b), arriving at a conclusion from shared premises, and then in turn treating that conclusion as a premise from which to derive new conclusions. Sometimes Glaucon and others seem too ready to agree with Socrates, and they often fail to critically scrutinize his claims, but an important feature of Socrates method is its cooperative, agreementsecuring nature. (This is perhaps surprising in light of cinematic and televisual depictions of the Socratic method as a matter of antagonistic intellectual combat between a knowing professor and a terrified firstyear law student.) So before putting the definition of political justice to work in order to understand personal justice, Socrates wants to be sure that Glaucon accepts the conclusion of their investigation into the nature of political justice. Given the focus on theoretical city-building, it is easy to forget that the political theorizing is not an end in itself but rather a means to grasping what justice is for the individual. Now Socrates must Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.06 114 Platos Republic: An Introduction make good on the promissory note he wrote in Book II and justify the assumption that city and soul are sufficiently analogous so that what is true of the former is also true of the latter. Platonic Psychology: The Divided Soul (4.434d441c) If Socrates is to apply what has come to light in the city to an individual (4.434e), he first needs to show that city and soul have the same structure. He has been proceeding on the assumption that they do, and now it is time to make good on the big if he has been operating with: if an individual has these same three parts in his soul (4.435b). In a few pages, he thinks he has done the job, noting we are pretty much agreed that the same number and the same kinds of classes as are in the city are also in the soul of each individual (4.441c). How does he get there? Earlier, when discussing personal, Socrates suggested that the commonsense idea of self-control was puzzling, for it seems ridiculous (4.430e) that something could control itself. But he makes sense of this intuitive account of moderation by positing that the soul has parts. In a moderate persons soul, a better, rational part is in charge, governing by calculation in accordance with understanding and correct belief (4.431c) the worse part, which contains all kinds of diverse desires, pleasures, and pains (4.431c). He now makes explicit the principle by which he arrived at this distinction, which I will call the Opposition Principle: the same thing will not be willing to do or undergo opposites in the same part of itself, in relation to the same thing, at the same time. So, if we ever find this happening in the soul, we will know that we are not dealing with one thing but many (4.436b). To get a sense of the Opposition Principle, suppose you have one hand in a bucket of hot water and the other in a bucket of cold water. It seems that you are both hot and coldbut how could that be, since hot and cold are opposites? The Opposition Principle tells us you must have parts, which indeed you (obviously) do: one of your parts is hot while the other is cold. Another example: if I am standing in one spot, but nodding my head, am I moving or not? The answer seems to be both yes and no: I am not changing my location, so in that sense I am not moving, but in another sense, I am moving, since I am moving my The Republics First Question Answered at Last 115 head. The Opposition Principle tells us that I must have parts, since I can simultaneously undergo or instantiate incompatible opposites. Most of us have had the experience of wanting to do something but not doing it, even when we are able. I am really hungry and there is a piece of pizza right in front of me, but I do not eat itperhaps because I see that it is your pizza, not mine, and I think that I should not take what is not mine. I am really jonesing for a cigarette, yet I do not light upnot because there are no cigarettes available, but because I am trying to quit. Whatever the details, the question is essentially the same: what explains my having a desire or appetite that I am able to fulfill but do not? It might be that I have another desire and that both of these desires cannot be satisfied at the same time. If I am really, really hungry and really, really, really tired, whichever one is strongerwhichever has more reallyswill probably determine what I do. A conflict of desires shows that I have many desires, but not that my soul is divided. But the kinds of cases Socrates discusses are not like that: they are cases in which I choose not to act on my desire because I have a reason not to do so. In these sorts of cases the Opposition Principle tells me that my soul must have at least two parts, one appetitive and one rational. But Socrates soon comes to see that there must be a third part, as well: Do we do these things with the same part of ourselves, or do we do them with three different parts? Do we learn with one part, get angry with another and with some third part desire the pleasure of food, drink, sex, and the others that are closely akin to them? Or, when we set out after something, do we act with the whole of our soul, in each case? (4.436a) Now he suggests there is a third part, spirit, in addition to reason and appetite. In contrast to the rational part, which is the part of the soul with which it calculates (4.439d), and the irrational appetitive part, which is the part with which it lusts, hungers, thirsts, and gets excited by other appetites (4.439d), there is also the spirited part[,] by which we get angry (4.439e)both at others, when we have been treated unjustly, and also at ourselves, when we have acted unjustly. To illustrate this, Socrates offers the rather disturbing example of Leontius necrophilia: He had an appetite to look at them but at the same time he was disgusted and turned away. For a time he struggled with himself and covered his face, but, finally, overpowered by the appetite, he pushed his eyes wide 116 Platos Republic: An Introduction open and rushed towards the corpses, saying, Look for yourselves, you evil wretches, take your fill of the beautiful sight! (4.439e) Leontius spirited element makes war against the appetites (4.440a) but ultimately loses, giving in to a desire that Leontius himself is disgusted bywhich results in his self-directed anger. Let us pause for a moment and consider the role disgust plays in the Republic. Socrates has praised the person of godlike character who is disgusted by injustice (2.366c), in contrast to the unjust person who has no scruples about [i.e., is not disgusted by] doing injustice (2.362b). The would-be guardians are being educated to disdain to act (3.388a)to be disgusted to actas Thrasymachus would. We have already remarked upon the moral point of their aesthetic education, the point of which is to acquire the right distastes (3.401e). It is the same Greek word in all these passages, (duschertain): to be unable to endure, to be disgusted with. Disgust at rotting meat seems to be a universal human reaction, one we come to naturally, without learning. But moral disgust is a product of education and upbringing. Someone raised on the Thrasymachus plan will fail to be appropriately disgusted at wrongdoing and other modes of moral ugliness. And unlike its physiological counterpart, moral disgust is conceptual. It is not the thought of rotting meat that disgusts us, it is the smell of the rotting meat itself (although physical revulsion may well arise if I imagine rotting meat robustly enough). I should be morally disgusted at witnessing an outrageous act of injustice, butif I have been properly raisedI should also feel moral disgust at the thought of injustice and be angry about it. Leontius was disgusted both by the corpses and by his attraction to them, which suggests that his problem is not that he lacks the right distastes (3.401a). His problem, rather, is that his soul is not properly aligned: his spirited part is not strong enough to overcome his appetites and thus it sides with them rather than with reason. A conflict between reason and desire, between what we think we ought to do and what we want to do, is a common feature of the human condition. On Platos psychologyliterally, his logos of the psychthe conflict requires a third party for its resolution: spirit, which sides with reason in a wellordered soul, and with appetite in a poorly ordered one. Spirit is by nature the helper of the rational part, Socrates says, but to call the arrangement natural is not to say that it will occur all by itself, without The Republics First Question Answered at Last 117 outside help, but rather that this is what spirits function is. Spirit will perform its natural function provided that it has not been corrupted by a bad upbringing (4.441a). It is telling that spirit is defined as the part of the soul we get angry with, for anger of a particularly moral typeresentment or indignationcan be the appropriate emotional response to injustice suffered or witnessed, respectively, just as shame, a kind of moral selfdisgust, is the proper emotional response to having acted unjustly. Spirit, like reason but unlike appetite, is evaluative, but its evaluative scope is narrower than reasons. Spirit seeks to protect its distinctive good, honor, and views the actions of oneself and others through this lens. Many philosophers agree with Jeffrie Murphys view that wrongdoing can communicate the demeaning message that it is permissible for the wrongdoer to treat the victim as they do, and that the victims anger, which often involves a desire to retaliate, can be seen as a way of denying the wrongdoers demeaning message.1 While spirit is able to see what is good and bad for it and to defend its own turf, it is not able to see what is good all things consideredthat is reasons task. When one has been wronged, the spirited part of the soul typically burns with anger and a desire for revenge, to negate the demeaning message the wrongdoing seems to encode. It would be good to harm him in return! it seems to say. But spirit is the part that is angry without calculation (4.441c). Where spirit is passionate and hot, reason is detached and cool, seeking what is advantageous for each part and for the whole soul (4.442c) rather than for any particular part. Reason might offer an alternative interpretation of the event that has angered passion, suggesting perhaps that the wrongdoer did not mean it that way or that it was an accident, etc., and thus that spirits anger is unjustified, so retaliation is inappropriate in this case. Or reason might reject retaliation altogether since it is never just to harm anyone (1.335e), as Socrates argued in Book I. The upshot of all this is that spirit is distinct from appetite and reason, though it shares affinities with each. In a well-ordered soul, spirit can be called to heel by the reason within [] like a dog by a shepherd (4.440d). Of course, this order must be cultivated from an early age, by the proper 1 Jeffrie Murphy, Forgiveness and Resentment, in Jeffrie Murphy and Jean Hampton, Forgiveness and Mercy (New York: Cambridge University Press, 1988), p. 25. 118 Platos Republic: An Introduction balance of musical and physical training. Overdoing physical training results in someone who is under-responsive to the demands of reason and who, like a rogue soldier, is unable or unwilling to obey orders. Underdoing physical education results in someone unable to subdue the appetites and passions. Readers familiar with Freuds psychology will see an intriguing parallel between the roles reason, appetite, and spirit play in Platos psychology and the roles ego, id, and super-ego play in Freuds. The Personal Virtues (4.441c444e) Having secured agreement that the soul has the same three-part structure as the ideal city, Socrates has justified to his companions satisfaction the dangling if at the heart of their method of investigating personal justice. If the assumption that city and soul are isomorphicthat they have the same three-part structurewere false, then we would have no reason to think that anything we have discovered about the nature of the political virtues tells us anything about the nature of the personal virtues. But having justified the hypothesis that underlies their methodat least to the satisfaction of Glaucon and Adeimantusthey can now apply what has come to light in the city to an individual (4.434e). Socrates makes quick work of the first three personal virtues, each of which is parallel to the corresponding political virtue. Just as political courage involves preserving law-inculcated beliefs about what are appropriate objects of fear, personal courage is not the preservation of innate or natural or accidentally acquired beliefs about what is to be feared but rather the declarations of reason about what is to be feared and what is not (4.442c). In a well-ordered soul, the rational part is the part making these declarations, since it is the part capable of knowledge of what is advantageous for each part and for the whole soul (4.447c), which is wisdom. As with political wisdom, personal wisdom requires the capacity to see the big picture. We encounter a problem when we try to map political moderation onto the individual soul. Like political moderation, personal moderation involves harmonythe Greek word is (sumphnia), whence the English word symphonybetween the rational and appetitive parts of the soul. With political moderation, this agreement is not merely practical, as when we say things like, cabin life really agrees with him, or when The Republics First Question Answered at Last 119 subject and verb agree in a grammatically coherent sentence. It is also cognitive: the ruler and the ruled believe in common that the rational part should rule (4.442c). But in the soul, the irrational appetites are parties to the agreement, and it is hard to see how mere appetites like hunger and thirst can agree with anything in the cognitive sense. One implication of the otherwise puzzling claim that each appetite itself is only for its natural object (4.437e) is that the appetites are non-cognitive, nonevaluative drives incapable of belief, judgment, and agreement. There is no corresponding head-scratching about the craftspeople agreeing with the guardians that the latter should govern the polis, since the craftspeople are people and thus capable of agreeing and disagreeing with claims or propositions. Personifying the parts of the soul helps us to make sense of Socrates account of moderation as a personal virtue, but in addition to the weirdness of thinking of appetites as being like persons, capable of forming beliefs and of making agreements, personifying the parts of the soul puts us on the road to an infinite regress: a persons soul comprises three parts, each of which is itself a miniature person or is like one; but then each of these miniature sub-persons would comprise even more miniature sub-sub-persons, and on and on. Like the poet Walt Whitman, we contain multitudes, apparently. Perhaps Socrates talk of agreement between the rational and irrational parts should be taken metaphorically. Socrates regularly appeals to metaphors in the Republic, such as the famous Allegory of the Cave and the less famous (but no less important) metaphors of the Sun and the Divided Line, which we will soon be exploring. But while thinking of personification metaphorically staves off the looming infinite regress, it leaves unexplained just how the irrational and rational parts come to an agreement. Are we letting Socrates off the hook too easily if we accept his metaphorical explanation? Albert Camus raised a parallel worry about metaphorically explaining the atom by appealing to the solar system: You tell me of an invisible planetary system in which electrons gravitate around a nucleus. You explain this world to me with an image. I realize that you have been reduced to poetry [] So that science that was to 120 Platos Republic: An Introduction teach me everything ends up in a hypothesis, that lucidity founders in metaphor, that uncertainty is resolved in a work of art.2 Though I understand his complaint, it seems that Camus fails to appreciate the cognitive power of metaphor, which is odd, given the centrality of the metaphor of Sisyphus to his account of the human condition. Are metaphorical explanations intrinsically problematic, as Camus seems to suggest? Metaphorical explanations are problematic when the metaphor that is offered to clarify the target concept is itself unclear or insufficiently understood. If the physics and nature of the solar system are well understood, why would appealing to the metaphor of the solar system be problematic? Perhaps Plato is here reminding us that we have agreed to forgo the longer and fuller road that leads to precise answer[s] (4.435c) in favor of a less demanding path that leads to a vantage point from which we see the same truths as we would from the more demanding path, but we see them less clearly and distinctly, from a distance. Walking the longer road of dialectic requires doing without hypotheses and metaphors, Socrates tells us later (6.511ae, 7.533c), but we will find them helpful while walking the less demanding trail we are on. Interestingly enough, Socrates does not exactly go in for personification of the souls parts in a metaphor he explicitly endorses later in the Republic. In the image of the soul in words (9.588b) he offers in Book IX, the appetitive part is not a person but rather a multicolored beast with a ring of many heads that it can grow and change at will (9.488c). While we might worry about the capacity of such a creature to form beliefs and agreements, remember that in distinguishing political courage from its natural analogue, which resembles but strictly speaking is not courage, Socrates notes that animals and slaves can possess correct belief about what is appropriately feared, however such beliefs are not the result of education [ nor] inculcated by law (4.430b) and thus they cannot possess courage proper but only its natural facsimile. While the hydra-headed beast representing the appetites can come to obey the commands issued by the rational part, as a dog can come to 2 Albert Camus, The Myth of Sisyphus, trans. by Justin OBrien (New York: Vintage International, 2018), p. 20. The Republics First Question Answered at Last 121 obey its masters commands, it is a stretch to think the beast or the dog agrees in the robust cognitive sense required. So it seems there is a glitch in the city-soul analogy, but perhaps such glitches are to be expected on the less precise path we are treading, since an analogy need not be perfect for it to be correct and helpful. Personal Justice: Intrapersonal Being versus Interpersonal Doing (4.443c444e) Finally, we get Platos answer to the Republics first question. Just as a city is just when each class does its own work, a person is just when each part of the soul does its own work. A person who possesses a just soul will do their own work: bakers will bake, cobblers will cobble, auxiliaries will defend, guardians will rule, etc. But the essence of justice is the harmony of the souls parts, not the individuals acting in certain ways. Socrates definition of justice is strikingly different from the definitions Polemarchus and Cephalus offered in Book I. To think of justice as telling the truth and paying ones debts or to think of it as benefiting ones friends and harming ones enemies is to think of justice primarily in terms of how one acts toward others. While Socrates thinks that the just person will treat others in certain ways, he does not think of justice primarily in terms of action: Justice [] is not concerned with someone doing his own externally, but with what is inside him, with what is truly himself and his own (4.443c). So where Cephalus and Polemarchus, both spokesmen for the commonsense morality of the day, think of justice as a matter of what one does, Socrates thinks of it as primarily a matter of how one is, of what one is like, internally. The essence of justice is not to be found in external, interpersonal doing, but rather in internal, intrapersonal being. That is quite a shiftso much so that some philosophers think that Socrates has changed the subject and indeed has committed the fallacy of irrelevance.3 Although I understand the point of this objection, I cannot say that I find it compelling. Socrates has not really changed the subject 3 David Sachs, A Fallacy in Platos Republic, Philosophical Review, 72 (1963), 14158. The first of many responses is Raphael Demos, A Fallacy in Platos Republic?, Philosophical Review, 73 (1964), 39598. 122 Platos Republic: An Introduction so much as deepened it. Polemarchus is thinking of justice in terms of action, but Socrates argues that it is something more fundamental than that, that Polemarchus thinking is literally too superficial: it is looking at the surface manifestations of justice without understanding its underlying essence, just as someone who thinks of water in terms of clarity and wetness is missing its molecular essence. It is not that Socrates is unconcerned with just actions, but rather than he thinks they are really merely expressions of the underlying virtue, to be explained in terms of inner character: the action is just and fine that preserves this inner harmony and helps achieve it (4.443e). As we noted earlier, Plato is offering what is nowadays called a virtue ethics, which takes the virtues to be morally fundamental. Consequentialist moral philosophers like John Stuart Mill think that good outcomes are morally basic, explaining right action and virtuous character in terms of those outcomes: an action is right if and only if it produces the best possible (or a sufficiently good) outcome, and a virtue is a reliable disposition to bring about good outcomes. Deontological moral philosophers such as Immanuel Kant deny that right action is to be explained in terms of good consequences, thinking that certain kinds of action are right in themselves; for deontologists like Kant, virtues are dispositions to do ones duty. Although this is a bit of a simplification, moral theories can be distinguished by which family of moral conceptsvirtues, outcomes, dutiesthey take to be explanatorily basic in the sense of explaining or defining the other moral concepts. Although deontology and consequentialism have dominated modern moral philosophizing in the English-speaking world for several centuries, virtue ethics has enjoyed a revival in recent decades. The basic idea, really, is that being a certain kind of person is morally more fundamental that doing certain kinds of actions. While the consequentialists and deontologists focus on actions although they differ strenuously in what explains why right actions are rightvirtue ethicists focus on persons and their characters, thinking that someone in whom the virtues have been cultivated (by upbringing, education, and individual effort) can be trusted to figure out what action to perform in whatever circumstances they find themselves. So, for a virtue ethicist such as Plato, an action is just because it is the sort of action a just person would perform in the circumstances. Now, The Republics First Question Answered at Last 123 merely doing what the just person does is not enough to make one just: there is a distinction between doing a just act and being just. If I am doing what the just person would do, then I am acting justly, but I might not yet possess the virtue of justice. Platos student Aristotle insisted that to act justly, I must do what the just person does; but to be just, to possess the virtue of justice, I must perform just acts as the just person performs them. I must be properly motivated, which requires at a minimum that I be motivated by what is fine or noble (what is kalon, that crucial concept we encountered in Books II and III) rather than by self-interest, and that, with a few exceptions we enjoy or at least are not internally resistant to performing the action. Socrates puts his definition to the test by asking Glaucon what kind of acts the just person, as they have defined her or him, will and will not perform. Socrates is asking Glaucon whether the proposed definition of personal justice squares with commonsense. If the just person, as conceived of by Socrates, would rob temples, steal, betray friends, or break contracts (4.443a)a list of unjust actions which Thrasymachus earlier specified as parts of injustice (1.344a) and which will be noted later as typical of people with tyrannical souls (9.575b)then the definition must be rejected, just as Cephalus and Polemarchus definitions were rejected for having implications that they themselves could not accept. If Socrates definition implied that a just person would perform such actions, it would theoretically be open to Glaucon to still accept the definition and change his mind about the moral status of thievery, temple robbery, betrayal, etc. But that would sound the death-knell for Socrates moral theory and would be rhetorically disastrous. Glaucon agrees that the just person would not perform these kinds of actions, the kinds of actions we can expect of someone wearing Gyges ring, of someone who thinks they can do injustice with impunity (2.360c). Socrates thinks his just person is incorruptible: they are (adamantinos) (1.360b): adamantine, made of steel, unshakably committed to justice and disgusted by injustice. As Socrates has defined it, justice (which, we should remember, is best thought of as virtue generally) is a kind of inner, psychic health: Virtue seems, then, to be a kind of health, fine condition, and wellbeing of the soul (4.444d). This is unsurprising, given Socrates moral realism. There are facts about what health is and what contributes to it, and we 124 Platos Republic: An Introduction are likely to roll our eyes at someone who says, Whos to say that a diet of potato chips and ice cream is unhealthy? Experts and indeed anyone who understands nutrition is to say, we want to respond. As a kind of inner health and harmony, virtue is similarly susceptible to this same kind of realism. If Socrates is right, there turn out to be moral facts, just as there are dietary factsand what those facts are is not up to us in any meaningful way. We may be unaware of these facts, but we discover them, we do not invent them. There is an objection we should address before closing. The objection turns on Socrates emphasis on inner harmony in his account of justice. For example, he says that the just person harmonizes the three parts of himself like three limiting notes in a musical scalehigh, low, and middle (4.443d), that he becomes entirely one, moderate and harmonious (4.443e); moreover, the action is just [] that preserves this inner harmony and helps achieve it (4.443e). The objection is that inner harmony is compatible with injustice. Consider a harmonious psychopath in whom reason, with the aid of spirit, rules the appetites. The psychopath does not really want to kill and eat other human beings, but believes that reason commands him to do so. So, the objection goes, if a harmonious soul is a just soul, it follows that a Socratically just person could do these awful things. But clearly a just person would not murder and cannibalize (let alone rob temples and break promises), so Socrates account must be rejected. Given what he says in Book IX, we can imagine that Socrates might respond by insisting that our harmonious psychopath has a tyrannical soul, which is highly disordered and unharmoniousthat our imagined counter-example is not really conceivable. But this seems to simply beg the question, to assume the truth of the very thing Socrates is supposed to be arguing for. A better response would be to point out that while harmony is a necessary condition of a souls being just (that is, a soul cannot be just without also being harmonious), it is not by itself sufficient (that is, it is false that any soul that is harmonious is thereby just). It is not that a harmonious soul is a just soul, as the objection assumes, but rather that a just soul is a harmonious soul. It is not enough that the rational part governs, Socrates should reply; it must get things right: wisdom is a kind of knowledge and knowledge requires truthwe can only know what is true, and it is not true that The Republics First Question Answered at Last 125 murder and cannibalism are morally permissible, other things being equal. We can probably imagine circumstances in which they might be, but the remorseless, harmonious psychopath we have imagined is not in such a situation. It should not be surprising that Socrates response presupposes moral realism. He thinks that moral knowledge, which presupposes moral truth, is possible. Such knowledge is rare and limited to philosopher-queens and -kings, but it is possible. Readers who are more skeptical will take this as a point of weaknessnot because they themselves reject moral realism (though some surely will) but rather because Socrates response presupposes moral realism without ever arguing for it. Even if we share his belief that there are genuine moral truths, we might find ourselves in a situation analogous to the situation Glaucon and Adeimantus found themselves in in Book II, agreeing with Socrates but seeing that our belief in moral realism is not justified. Of course, that does not make it false, but it leaves us in an epistemically perilous state. Socrates, we should remember, does not claim to know that moral realism is true; he is working with what his interlocutors believe, so his assuming the truth of moral realism is not problematic from within the framework of the Republic. But from outside that framework, as critical readers and thinkers, we should find it problematic, if we agree with him but can offer no arguments that would justify that agreement. Many readers will find this account of justice intuitively appealing, especially as it places reason at the centeror, perhaps better, at the helmof a well-lived life. Socrates will discuss the varieties of unjust souls in Books VIII and IX, but it will be helpful to trace one out here, if only briefly, in order to give us a richer sense of this account of justice. A clear, illustrative contrast is with a soul (and city) he deems oligarchic, one which takes amassing wealth to be lifes ultimate purpose. While the just person loves virtue, the oligarch loves wealth. As Socrates describes the oligarch, they are still more or less conventionally decent, though they are likely to cheat a bit if they can do so with impunity. In terms of their souls structure, the most distinctive contrast is that while reason governs the just persons soul, appetitein particular the desire for moneygoverns the money-loving oligarchs. For Plato, in a well-ordered and thus just soul, reason determines which ends and 126 Platos Republic: An Introduction goals one ought to pursue. This is its task, a task that requires the personal virtue of wisdom in order to be done well. But the oligarchic money-lover has appetite setting their ends: He makes the rational and spirited parts sit on the ground beneath appetite, one on either side, reducing them to slaves (8.553c). In contemporary philosophical lingo, the money-lover reduces reason to the purely instrumental role of determining the best means to achieve the ends set by appetite. It is not that figuring out the most effective means to a given end is not a task for reason; it surely is. But that is not all reason is good for, and indeed, important as such reasoning is, it is decidedly secondary in importance, in Platos view, to determining what is good in itself, what is worth pursuing as an end. The problem, Plato thinks, is that reason has only this instrumental role in the money-lovers soul and that in determining what ends and goals to pursue, appetite is taking over a task that does not properly belong to it. Appetite is meddling and not doing its own work, as the Specialization Principle and justice require. Reason, not appetite, is supposed to determine which things are good, so a soul in which appetite is doing reasons work is unjust. If we are reluctant to label as unjust souls whose possessors adhere to conventional morality despite being governed by appetite rather than reasonthe example of Cephalus immediately comes to mind we can at least regard them as non-just, reserving unjust for more obviously bad folk. Though many of us are no doubt inclined to agree with Plato about the centrality of reason to a well-lived life, we would do well to remember that great eighteenth-century Scottish philosopher David Hume disagrees strenuously with Plato about the role reason should (and indeed can) play in a well-lived life. Hume famously says, Reason is and ought only to be the slave of the passions,4 but Hume is emphatically not suggesting that we should give ourselves over to a passion for money; instead, he is making a point about human psychology that plays up the affective, emotional side of our nature and downplays the rational. We regularly mistake the calm passionssuch as benevolence, kindness to children, and the general appetite for goodfor reason, since they lack the force of violent passions such as anger and romantic love. We will 4 Hume, Treatise, p. 415 (II.iii.3). The Republics First Question Answered at Last 127 not settle Humes disagreement with Plato here, but I raise it to remind readers that, despite the prominence of reason in the history of Western philosophy, the issue is, like most fundamental philosophical issues, not settled. Hopefully this brief foray into the oligarchic soul helps to illustrate Platos definition of justice. Some Suggestions for Further Reading Readers interested in a philosophically astute discussion of the threepart soul will want to read Chapter 13 (Republic IV: The Division of the Soul) of Terence Irwin, Platos Ethics (New York: Oxford University Press, 1995), pp. 20322, which has informed my understanding of Platos psychology. Irwin is a leading scholar of ancient philosophy and the book as a whole is extraordinarily good, covering not just the Republic but many other dialogues as well. Plato and the Divided Self, ed. by Rachel Barney, Tad Brennan, and Charles Brittain (New York: Cambridge University Press, 2012), https://doi.org/10.1017/cbo9780511977831, contains excellent essays on Platos division of the soul in the Republic and elsewhere. For an excellent discussion of the concept of virtue, both epistemic and moral, interested readers should see Heather Battaly, Virtue (Malden, MA: Polity Press, 2015). Readers interested in exploring the biological, social, and philosophical nature of disgust should see William Ian Millers The Anatomy of Disgust (Cambridge, MA: Harvard University Press, 1998), along with a helpful review: Martha Nussbaum, Foul Play, The New Republic, 217.20 (1997), 3238. Readers interested in metaphor will find Zoltn Kvecses, Metaphor: A Practical Introduction, 2nd ed. (New York: Oxford University Press, 2010) well worth their attention. Readers interested in Humes view that sentiment, not reason, is the basis of morality, should see the first two sections of Book III of his classic A Treatise of Human Nature, Moral Distinctions Not Derivd From Reason and Moral Distinctions Derivd From a Moral Sense. The 128 Platos Republic: An Introduction Treatise is available in many editions and readers will find a modernized version of the Treatise (and most significant philosophical texts of the early modern period) at Jonathan Bennetts wonderfully helpful Early Modern Texts (http://www.earlymoderntexts.com/). Readers interested in parallels between Plato and Freud might start with A.W. Price, Plato and Freud, in The Person and the Human Mind: Issues in Ancient and Modern Philosophy, ed. by Christopher Gill (Oxford: Clarendon Press, 1990). For an engaging account of Freuds philosophical significance, see Jonathan Lear, Freud, 2nd ed. (New York: Routledge, 2015), https://doi.org/10.4324/9781315771915, part of the excellent Routledge Philosophers series. Readers curious about the potential permissibility of cannibalism will find a fascinating discussion in Peter Suber, The Case of the Speluncean Explorers: Nine New Opinions (New York: Routledge, 1998), which includes and expands on Lon Fuller, The Case of the Speluncean Explorers, Harvard Law Review, 62 (1949), 61645, on the occasion of its 50th anniversary. For an excellent exploration of the relations between virtue and health, interested readers should see Paul Bloomfield, Moral Reality (New York: Oxford University Press, 2001), https://doi.org/10.1093/0195137132.00 1.0001. Ernst Herter, Amazonenkampf (1891). Photograph by Mutter Erde (2017), Wikimedia, Public Domain, https://upload. wikimedia.org/wikipedia/commons/6/65/Ernst_Herter_-_ Amazonenkampf%2C_c._1891.jpg 7. Questions about the Ideal Polis: The Three Waves, Book V Having answered the Republics first question, Plato has Socrates immediately start in on its second: whether it is more profitable to act justly, live in a fine way, and be just, whether one is known to be so or not (4.445a). Since his method is to work with claims that his interlocutors believe, we might have expected Socrates to pause and ask if anyone has any questions about the definition of justice they have arrived at, but instead he immediately starts in on the Republics second question on the final page of Book IV. But as Book V begins, Polemarchus, who has been silent since Book I, jumps back into the fray, piping up with some questions which will lead to a digression (8.543c), as Socrates later puts it, that comprises Books V, VI, and VII, taking up about one hundred pages of the Greek text. Literary Artistry as a Way of Doing Philosophy (5.449bd) The opening of Book V is subtly but strikingly similar to the opening of Book I, and it is worth pausing to consider Platos literary way of making a philosophical point. Book I, readers will remember, begins with Socrates and Glaucon returning to Athens proper from its port, the Piraeus. Polemarchus unnamed slave bids them to wait for his master, after the slave caught hold of [Socrates] cloak (1.327b). In Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.07 132 Platos Republic: An Introduction the banter that follows, Socrates playfully asks if Polemarchus will let them go (1.327c). It is striking and clearly no accident that this scene is more or less repeated with the same vocabulary at the beginning of Book V: Polemarchus took hold of [Adeimantus] cloak asking, Shall we let it go?. When Adeimantus replies in the negative, Socrates asks, What is it that you will not let go?, to which Adeimantus replies, You (5.449b). What is Plato up to here? Why does he reprise the beginning of Book I here at the outset of Book V, with the same vocabulary? Although it may be just pleasing literary symmetry enjoyable for its own sake, I suspect there is more to it than that. I think that Plato is using literary form to make a substantive point about the nature of philosophy: philosophy is always starting over, always examining its foundations. Though we have travelled quite a distance from the opening scene, the conclusions it ultimately led to, especially the account of justice as each part of the soul doing its own work, need to be scrutinized. Doing so is important given the method Socrates and company have adopted, which relies on shared agreement about premises to derive conclusions. Plato might have made this point more directly, but making the point so subtly as almost certainly to be missed the first time around seems not just a more elegant but a more effective way of making the point that doing philosophy well invariably involves examining ones conclusions and starting points. It is more effective, I think, since he lets his readers make this point for themselves, by prompting us to ask why he rhymes the beginnings of Books I and V. And indeed the conclusion I have drawn, that he is making a point about the nature of philosophy, is one that should itself be revisited, as there may be more going on than thator he might be making a different point altogether. We will not pursue it any further, but I hope at least that this discussion helps readers to appreciate not just the literary quality of the Republic but also the way in which Plato seamlessly joins literary form and philosophical content. It is one of the reasons that the Republic is a treasure that bears repeated re-reading. Questions about the Ideal Polis 133 The Three Waves (5.450a451c) Adeimantus and Polemarchus are prompted by the implications of a nugget of commonsense Greek wisdom that Socrates utters in Book IV after giving the rulers of the ideal city their charge to guard above everything else the program of education and upbringing they worked out in Books II and III: all the other things we are omitting, for example, that marriage, the having of wives and the procreation of children must be governed as far as possible by the old proverb: Friends possess everything in common (4.424a). While Socrates wants to avoid exploring such details, Adeimantus and Polemarchus insist that he do so. It is not that they disagree with the proverb Socrates has appealed to, but rather that it requires an explanation ( [logos]) (5.449c): they want its implications explained and justified, since they run so contrary to Athenian social arrangements and customs. When even Thrasymachus agrees, Socrates has little choice but to accede to their wishes, even though he would prefer to avoid this swarm of arguments his friends have stirred up. As at the beginning of Book II, Glaucon and Adeimantus agree with Socrates, but they are sufficiently self-aware to see that their belief is unjustified; hence their insistence that Socrates provide an explanationa logos. The social arrangements proposed or implied in the design of the ideal city will be scrutinized by two questions: Is it possible? and Is it optimal? The kind of possibility in question here is not logical possibility but rather something more along the lines of practicality: could this arrangement be realized in an actual city? If the answer is yes, they turn to the second question, which asks whether this arrangement would be optimal or at least beneficial. In a nutshell, the questions can be collapsed into one: Could we really live this way, and if so, should wewould it be good for us if we did? In one of his not infrequent confessions of pessimism or trepidation, Socrates is leery of the line of inquiry Adeimantus and company are insisting on, since mistakes about what is the best way for humans to liveand here it is good to remember that their discussion concerns no ordinary topic but the way we ought to live (1.352d)can be disastrous. A mistake here will likely lead to a true falsehood, the very worst thing to believe. But Socrates fares forward, facing each of the Three Waves. The 134 Platos Republic: An Introduction metaphor of the wave is a powerful one for the residents of a sea-faring polis, especially as the discussion that constitutes the Republic takes place in the Piraeus, the port of Athens. The waves come in order of increasing severity: the first concerns whether women can be guardians; the second concerns the abolition or de-privatization of the traditional family; the third concerns the ideal city itself. We will look at the first two in this chapter and explore the third in the next, since Socrates takes the end of Book V and the whole of Books VI and VII to address it. The First Wave: Can Women Be Guardians? (5.451c457c) Since friends have all things in common and the citizens of the ideal polis are friendsbringing about this friendship should be one of the fruits of the Noble Falsehoodthe citizens will share the same upbringing and education, as well as the same jobs. There is no reason, Socrates thinks, why being female is by itself a disqualifier. Like the people listening to Socrates, many readers will be surprised by this, though probably for different reasons. Indeed, Glaucon and company find the very idea ridiculous, a complaint one encounters at least half a dozen times in one page of the Greek text (5.452). Physical education is an important part of the would-be guardians education, and by Athenian custom much of this, especially wrestling, occurs when the participants are naked. Thus they find it difficult to take Socrates proposal seriously. As is often the case in the Republic, in addition to the issue immediately at handhere, whether women can participate in the education required of would-be guardiansthere are deeper issues which transcend the boundaries of the Republic and which should be of interest even to those who regard the ideal polis as decidedly dystopic. One, of course, is the status of women; another is the status of societal norms. As Socrates diagnoses Glaucons reasoning, the idea of women wrestling naked is ridiculous because it is contrary to custom ( [para to ethos]) (5.452a). But why, Socrates asks, adhere to local custom? After all, at one point it was contrary to custom for men to wrestle naked, and that probably incited ridicule then, too. Since customs can change over time, perhaps we will give up the custom barring women from wrestling naked, too. Questions about the Ideal Polis 135 But Socrates has a deeper point to make than that, one that challenges the normative force of cultural customs, and one that should not surprise us, given his commitment to philosophical reflection. A cultural relativist holds that an action is right (and, alternatively, wrong) if and only if ones culture approves (or, alternatively, disapproves) of it. That is all there is to rightness and wrongness; there is no culture-transcending standard by which to assess the norms of ones own culture or those of another. One problematic consequence of cultural relativismand remember that one way to test a claim is to consider its implications is that it makes the idea of moral progress nonsensical. Sure, we now disapprove of slavery and thus regard it as wrong, but that is not an improvement on the earlier standard; it is just a different standard. And what goes for one culture viewed over time goes for different cultures viewed at the same time: your culture holds that women should not vote, mine holds that they should. One is not better than another, on the relativists view: they are different, not better or worsebecause to hold that anti-slavery or pro-female suffrage norms are better than their opposites requires a higher, culture-transcending standard by which to assess those cultural standards, and these are the very things denied by the cultural relativist. The argument pattern here should be familiar: A implies B, and B is falseor, at least, the person we are talking with regards it as falseso A must also be false. Consider this argument: P1 If (A) cultural relativism is true then (B) the idea of moral progress is incoherent. P2 (not-B) The idea of moral progress is not incoherent. C Therefore, (not-A) cultural relativism is not true. The argument is logically valid, so a die-hard relativist wishing to deny its conclusion must either reject P1, holding that cultural relativism does not imply that moral progress is incoherent, or reject P2, conceding that the idea of moral progress is not coherent, after all. These are both tall orders, for relativism, holding that what ones culture approves of is right, implies that there is no standard by which to judge one cultures standards to be better than another cultures and there is no standard by which to assess my cultures former standards and its current standards. No standard is better; they are just 136 Platos Republic: An Introduction different. Since progress means change for the better, it is difficult to see how a cultural relativist could regard moral progress as coherent, given their insistence that there are no standards by which to assess a cultures standards. Socrates does not make the moral progress argument, but it is presumably something he would endorse, since he rejects the cultural relativism that takes ones cultures standards as sound just because they are ones cultures standards. It is foolish, he thinks, turning Glaucons objection back on him by employing the same word ( [geloios]), to think that anything besides the bad is ridiculous [] and it is foolish to take seriously any standard of what is fine and beautiful other than the good (5.452de). Socrates is not a nihilist or anarchist; he is not opposed to cultural norms and standards per seit would be odd if he were, given the amount of time he has so far devoted in the Republic to an educational program designed to cultivate the right ones. What he is opposed to is uncritical acceptance of ones cultures norms, to regarding them as correct or beyond question merely because they are the norms of ones culture. That fact that ones culture approves of x and y and disapproves of z is one thing; whether ones culture ought to do so is a different matter entirely. The subsequent books in the Republic will reveal something of what Socrates takes the good to be, but even if we find ourselves disagreeing down the road with his particular version of moral realism, we can agree with him about the role that critical reflection and reasoned argument ought to play in determining which norms a culture ought to possess. What was ridiculous to the eyes, Socrates says, faded away in the face of what argument showed to be the best (5.452d). Women wrestling naked seems ridiculous to Glaucon and his friends, but until one has scrutinized ones cultures standards, it is not clear that it really is ridiculous. Socrates critique of Glaucons appeal to what seems ridiculous echoes his earlier remarks on disgust and cultivating the right distastes. Finding something ridiculous differs from finding it disgusting: laughing at something is a much weaker form of disapproval than being nauseated by it. But they are both modes of disapproval, ways of registering that something is improper. These modes of disapproval are typically not rational: we are raised to find certain things ridiculous and certain things disgusting while we are young and unable to grasp Questions about the Ideal Polis 137 the reason (3.401a). Socrates calls on reason to help determine whether what seems absurd or disgusting really is absurd or disgusting, and if so, why. If we cannot justify our tastes and distastes, perhaps we ought to give them up. In his ideal polis, no one needs to give up the norms they have absorbed from their culture, because the educational system is supposed to guarantee that the only norms and values available for absorption are correct. But those of us not raised in utopias will need to scrutinize our cultures norms and values, since we cannot be sure those norms and values are correct. To my mind, the value of liberal education, and especially philosophical education, is to be found in their enabling us to better scrutinize and evaluate the norms, values, and beliefs we were raised to have, so that we are in a position to endorse some and reject others, thereby making our norms, beliefs, and values truly our own. Without critical scrutiny, these norms, values, and beliefs are not really our own, and we are not fully free: we might be free of interference, but we lack the freedom that comes from genuine, deep self-direction. (We will return to this distinction between negative and positive freedom below, in Chapter Twelve.) Having made his general point about cultural norms, Socrates brings the argument back to the question of whether having women as guardians is possible. In a move that is a model of intellectual fairness, Socrates decides to give the argument against ourselves (5.453a). That is, he articulates what he takes to be the best argument against the view he holds. It is worth pausing to admire this kind of intellectual fairness, especially as it seems in such short supply these days. How many of us, after all, are willing or able to give a fair hearing to political and moral arguments we disagree with, let alone give them a reasonable reconstruction? As we noted earlier, much political and moral debate traffics in the production and consumption of strawmen: we caricature the views of our opponents and then think we have refuted our opponents by knocking down these caricatures. A quick glance at the comments section of most online newspapers should provide ample evidence for the prevalence of strawmen. The argument Socrates considers is a powerful one, since it appeals to the Specialization Principle, which structures the economic life in the ideal polis and indeed is the basis of the definition of justice, in arguing against the view that women can be guardians. The Specialization 138 Platos Republic: An Introduction Principle implies that each must do his own work in accordance with his nature (5.453b). But of course, the natures of men and women are different (5.453e), so how can Socrates hold that men and women may perform the same tasks? Socrates position is self-contradictory, argues the imagined opponent: he cant endorse the Specialization Principle and hold that women can be guardians, since the former implies that the latter is false. It is a powerful argument, of just the sort that Socrates regularly gives against others. Although he acknowledges the arguments rhetorical force, he finds it philosophically unsatisfying, since it is an example of eristic, which was discussed briefly in Chapter Two. The opponent, perhaps unwittingly, is quarrelling or wrangling ( [erizein]), aiming to win the argument, rather than to get at the truth of the matter. The arguments main fault is that it fails to make a relevant distinction and so arrives at its conclusion illegitimately. Although it gets the Separation Principle right, it fails to distinguish different kinds of nature and employ the one that is relevant to the argument. Consider bald and long-haired men, for example Seinfelds George Costanza and the supermodel Fabio. Clearly their natures are different, but from that it does not follow that George cannot be a cobbler if Fabio is, because whether one is bald or has a full head of lustrous hair is irrelevant to the craft of cobbling. It is not that the bald and the tricho-luscious are not different, but rather that the difference between thembetween their naturesis not relevant to the issue at hand. Thinking otherwise, Socrates says, is ridiculous (5.454d). What is distinctive of a guardian-ruler is the kind of soul they have, a soul capable of wisdom, of knowledge of what is best for the city as a whole. The primary difference between men and women is biological or physical (somatic might be more precise): they differ only in this respect, that the females bear children while the males beget them (5.454d). There is no reason to think, Socrates insists, that this physical difference must make for a psychic difference. Consider a female doctor, a male doctor, and a male cobbler. If asked, Which two are more similar to each other than to the other?, you would rightly respond that you cannot answer the question until you know the relevant parameter of comparison. Physically, the male doctor and male cobbler are more similar to each other than either is to the female Questions about the Ideal Polis 139 doctor. Psychologically, the male doctor and female doctor are more similar to each other than either is to the male cobbler. The souls of cobblers differ in nature from the souls of doctors, being susceptible of acquiring a different kind of skillperhaps this is a difference between iron and bronze souls. But as naturally different as cobblers and doctors souls are from each other, they are more like each other than they are like the souls of guardians, who, rather than possessing a skill or craft, possess a virtue. All three possess knowledge, but the objects of knowledgehow to make shoes, how to cure the sick, what is best for the city as a wholeare strikingly different, and, as we saw earlier, skills are fundamentally different from virtues, insofar as skills are morally neutral while virtues are not. The upshot of all this is that men and women having all tasks in common, and especially the task of guardianship, is possible: it is not contrary to nature. While men may on average be physically stronger than women, this difference in physical strength is not relevant to ruling or soldiering, since it may well not hold in particular cases. As I write this, the world record for the marathon for men is roughly twelve and a half minutes faster than the world record for women (2:01:39 versus 2:14:04), but the fastest womens time is really fast, and is much, much faster than the overwhelming majority of men can run. It was the twenty-third fastest time run that day (13 October 2019) in the Chicago Marathon, faster than 24,604 of the men who completed the race. That men on average run or swim faster or lift more weight than women is irrelevant to what this particular woman and that particular man can do, and it is the particular persons qualifications that are relevant, not the average qualifications of groups they belong to. Having shown that it is possible for women to be guardians and to receive the same education as their male counterparts, Socrates makes short work of the other question, whether it is optimal. Given that the only thing standing in its way is unreasoned cultural prejudice, it is no wonder that Socrates regards this arrangement as for the best. After all, he reasons, why would you not have golden-souled guardians in charge, whatever their sex, given that physical difference is irrelevant to the task of ruling? 140 Platos Republic: An Introduction Is Plato a Feminist? Platos perhaps surprising insistence that women can be guardians prompts us to ask, Is Plato a feminist? To answer this question, we need to know what it is to be a feminist, a thornier task than it might at first seem. The Stanford Encyclopedia of Philosophy (an excellent, free, online resource) has half a dozen entries for different kinds of feminism and half a dozen again for feminist approaches to various philosophical topics such as knowledge, the self, science, ethics, etc. I am going to make the simplifying assumptionhopefully not an over-simplifying onethat at feminisms root is a belief in and commitment to gender equality. The idea here is that men and woman are morally equal, that being a woman is never in itself a reason to give a womans interests less weight. We know that Plato is not an egalitarian, but importing a contemporary moral principle (one animating the work of Peter Singer, among others) can shed helpful light on this sections question. The Principle of Equal Consideration of Interests (PECI, for short) holds that the interests of all parties affected by an action or decision ought to be given equal consideration unless there is a morally relevant fact or difference that justifies unequal consideration. The first thing to notice about the PECI is that it is a moral principle; it is not attempting to describe how people actually act and decide; rather, it is a principle about how we ought to act. A second thing to notice is that its currency is consideration, which is different than treatment. A teacher who gives every student the same grade treats the students equally, but this is not what the PECI demands. Instead, it demands that the teacher give equal consideration to all: they use the same standards to evaluate their work, do not play favorites, etc. There is a clear sense in which such a teacher is also treating their students equally, but it is worth noting how consideration and treatment differ. If there are 200 applicants for a job, the only way to treat all applicants equally in the strict sense is to hire all of them or none of them. What the PECI requires is that the prospective employer use fair standards and apply those standards equally. That is what I take a commitment to equal consideration to require. A third point worth mentioning is that the PECI mandates presumptive rather than absolute equality of consideration. It recognizes that there may be times when unequal consideration is called forbut Questions about the Ideal Polis 141 as the fourth point makes clear, unequal consideration is permissible only if there is a morally relevant difference between parties or a morally relevant fact that would justify unequal consideration. Psychologists are adept at discovering the factors that decision-makers take to be psychologically relevant and which explain why we often do not give equal consideration to all parties affected by our actions. But the PECI is a normative principle, not a descriptive one: it requires a morally relevant fact that justifies unequal consideration, not a psychologically relevant fact that explains it. A racist violates the PECI by taking racial difference to justify giving unequal consideration to the interests of those affected by their actions. They violate the PECI because, with very few exceptions, racial difference is not a morally relevant difference. Racial difference is clearlyand sadlypsychologically relevant to racists, since it helps to explain why they act and think as they do. But it is rarely morally relevant: other things being equal it does not justify giving unequal consideration based on race. In parallel fashion, a sexist takes sex-difference to be a morally relevant difference when it presumptively is not. This is not to say that race- and sex-differences are never relevant. If Brad Pitt complains to Variety that the director of an upcoming film about the life of Martin Luther King, Jr. is racist because they would not even consider him for the part, we might think he is joking, since in this instance racial identity seems quite morally relevant, not least because it would be offensive to have a white actor appear in blackface to play Dr King. More seriously, this is not to say that race- and sex-based affirmative action policies cannot be justified, but rather that they stand in need of justification: since the presumption is that race and sex are not morally relevant, the burden of justification falls on the person or policy appealing to them. Although Plato is no egalitarian, there is a sense in which he accepts the PECI. He takes the kind of soul one hasgold, silver, bronze, iron to be relevant to whether one is eligible to participate in governing the polis and indeed whether ones thoughts about governing the city should be given any consideration. Readers who are egalitarian democratsand that is democrat with a small d, implying not party affiliation but rather a view about who is entitled to have a say in how ones community is governedwill think that Plato is mistaken about this: every competent adult should have equal rights to political 142 Platos Republic: An Introduction participation. But that point aside, it is clear, I think, that Plato certainly accepts the PECI with respect to sex-difference: there is no way of life concerned with the management of the city that belongs to a woman because she is a woman or to a man because he is a man, but the various natures are distributed in the same way in both creatures. Women share by nature in every way of life just as men do (5.455d). In the lingo of the PECI, for Plato sex-difference is not a morally relevant difference that would justify giving unequal consideration to the interests of men and women. We should note that the attitude that Plato has Socrates express here is deeply at odds with Athenian attitudes of their day. Women played no role in governing Athens, and well-to-do women would never be seen by themselves outside the home. His attitude would have seemed less radical in Sparta, where women were sufficiently engaged in public life for Plutarch to be able to compile a volume entitled Sayings of Spartan Women. That certainly inclines us toward a yes answer to the question of whether Plato is a feminist. Affirmative support can also be found in the Second Wave, which we will get to shortly. Put briefly, Plato de-privatizes and indeed abolishes the traditional nuclear family, doing away with traditional marriage and child-rearing, and instead having children raised communally by people with a natural aptitude for it. To the extent that the traditional family can be a site of patriarchal oppression, limiting which roles and opportunities are available to women, Platos doing away with it lends support to the judgment that he is a feminist. But this very same point also provides a reason to doubt that Plato is a feminist. In addition to its commitment to gender-equality, feminism is plausibly characterized as committed to recognizing and overcoming gender-based oppression, where oppression is the systematic disadvantaging of one group for the benefit of another. Although Plato has Socrates argue that it is both possible and optimal for suitable women to be guardians in the ideal polis, there is no hint that he recognizes that his culture oppresses women; nor does he aim to liberate the women of the ideal polis from oppression: his motivation in advocating gender equality is that it benefits the polis, not that doing so is a matter of social justice or fairness. If women are liberated from oppression, it is accidental rather than intentional, which is a point in favor of a negative answer to the question of whether Plato is a feminist. Questions about the Ideal Polis 143 Another Second Wave issue that counts against Platos being a feminist is what we can call the asymmetry of possession. Possession is an asymmetrical relation: except in a metaphorical sense, I possess my possessions: they belong to me, I do not belong to them. Some relations, such as being siblings, are symmetrical: if Mary is my sibling, I am her sibling. But other relations, such as being a sister of, are asymmetrical: if Mary is my sister, it does not necessarily follow that I am Marys sister. Given that possession is asymmetrical, Socrates saying that all these women are to belong in common to all the men (5.457c [literally, they are to be (koinas): shared in common]) is problematic for thinking him a feminist. If Plato really were committed to gender equality, we would expect Socrates to then say something like, and of course all the men belong in common to all the women. But he does not, which suggests that women are not after all to be thought of as fully equal to men. The last reason against thinking that Plato (or at least Socrates, if I can depart for a moment from my practice of not worrying about distinguishing them) is not a feminist is one that many readers will already have noticed for themselves: the Republic is sprinkled with misogynistic remarks. For example, when discussing the irrational, appetitive part of the soul, Socrates says, one finds all kinds of diverse desires, pleasures, and pains, mostly in children, women, household slaves, and in those of the inferior majority who are called free (4.431c). Later in Book V he will characterize stripping corpses on the battlefield as small minded and womanish (5.469d). In both cases (and many others) he seems to be operating with a male-female binary in which the female pole is decidedly negative. This is perhaps the kicker: in Book VIII when disparaging democracy he bemoans the extent of the legal equality of men and women and of the freedom in the relations between them (8.563b). Could a real feminist regard equality before the law as a bad thing? It is hard to see how this could be the case. The conclusion, I think, is that although there are good points to be made on the other side, Plato is not, all things considered, a feminist. Given his time and place, his insistence that there can be philosopherqueens as well as philosopher-kings (7.540c) is surprising and laudatory, even if it falls short of what those of us today who are committed to gender equality and equity would hope for. 144 Platos Republic: An Introduction The Second Wave: Extending the Household to the Polis (5.457c471b) When discussing whether Plato was a feminist, I described the Second Wave as the abolition of the family. This is not quite accurate, since the operative notion for Plato is the notion of the household ( [oikia]), a wider notion than our notion of the family, though they are clearly related. Platos plan is to obliterate the boundaries between households so that the polis becomes one large oikia or household. There is some scholarly controversy about whether the extension of the household applies to everyone in the polis or just the auxiliaries and guardians. Much of what Socrates says suggests the latter, but since bronze and iron parents can have gold or silver children, it is hard to see how de-privatizing the family could work unless the city is one large household. Similarly, the seriousness with which he takes the city-soul analogy, when coupled with his view that the best city is most like a single person (5.462c), suggests the ideal of the polis as one big household. This is an interesting question, though perhaps of interest mainly to specialists, so, having raised it, I will set it to one side. We saw above that the women are to belong in common to all the men and, a related point which we did not mention above, none are to live privately with any man (5.457c). We met this absence of privacy earlier, when toward the very end of Book III Socrates described what life is like for guardians and auxiliaries in the ideal polis: they live a barracks life, like soldiers in a camp (3.416d), having no private property beyond what is wholly necessary (a qualification that allows a guardian to say things like, hey, thats my toothbrush) and no private dwellings. The end is nigh when guardians possess private land, houses, and currency (3.417a), since this will distract their focus away from what is good for the community and toward what is good for them individually. The Greek phrase being translated as private is a form of (idios), from which the English word idiot derives. But the implication is individuality in opposition to what is common or shared ( [koinos]) or public, rather than some sort of mental thickness or incapacity, though even our word retains a bit of this when we think of an idiot as living in his own world. We should try to avoid reading our modern notion of privacy into the text here; individual property would Questions about the Ideal Polis 145 do just as well as a translation, especially as idios often means simply individual elsewhere in the Republic (e.g., Thrasymachus argues that injustice is beneficial to the individual ( [idia(i)] (1.344a)) or unique or peculiar (e.g., Socrates insists that each craft benefits us in its own peculiar ( [idian] way (1.346a), though peculiar has its own misdirecting connotations). The children too will be possessed in common (5.457c), though here the rationale is quite surprising: they are possessed in common so that no parent will know his own offspring or any child his parent (5.457d). Socrates thinks that it is obvious that de-privatizing the family would be beneficial, thinking he need only address whether it is possible to put this arrangement into practice. In an all-too-rare expression of disagreement, Glaucon thinks that Socrates is mistaken on this score and insists that he justify his claim that doing away with the family is a good thing. Given the centrality of family to everyday, commonsense, moral thinking and to many readers conceptions of what a happy, well-lived life centers on, Socrates faces an uphill battle. Few readers, I suspect, will find what he says fully convincing and follow him all the way to the community pole of the individual-community duality we have seen at play in the Republic, but many will be willing to move the arrow a bit more in that direction if they give Socrates a fair hearing. There is a lot to dislike in what Socrates says here. Talk of eugenics and racial purity (5.460c) is beyond being merely creepy in a post-Holocaust world, and raising children in rearing pens (5.460c) seems to fail to do justice to human dignity, just as reducing marriage to state-sanctioned sexual hook-ups for the purposes of producing citizens fails to do justice to the dignity of marriage. The amount of deception guardians will use to rig the procreation lotteries (which determine who will have sex with whom, and when) will probably seem to most readers to be not merely innocuous verbal falsehoods, but rather indicative of governmental moral depravity. One need not think lying is absolutely forbiddenfew of us do, reallyto be troubled by lies that might even be beneficial. And many readers will doubt that the guardians lies will be beneficial, even if they are efficient. But there are also things to like in what Socrates says. He is concerned with civic unity, with the integrity of the ideal polis. The worst thing that 146 Platos Republic: An Introduction can happen to a city, he argues, is for it to be divided rather than united; whatever divides and dis-integrates a city is the greatest evil, he says at 5.462a, reprising and modifying a point he made when he defined political justice (4.434bc). We might disagree that this is the worst thing that can happen while conceding that Socrates has a point, that a fragmented, divided city or nation is in bad shape, not functioning well, not politically healthy. His concern with faction and internal strife was certainly shared by Americas founders, as for example one finds in Federalist #10, by James Madison (though readers familiar with the history of the early United States know how strife- and faction-ridden political life then was). A polis in which citizens say mine about the same things is a polis that is unified: if all the children are my children, I am unlikely to favor some over others; I will want all of the citys children to flourish and succeed, since I think of all of them as mine. It is because Socrates thinks that the best-governed city is one in which most people say mine and not mine about the same things in the same way (5.462c) that he thinks that an arrangement in which no mother [or father] knows her own child (5.460c) is optimal: it unifies the city, making it most like a single person (5.462c). In my state of Wisconsin, about 15% of the children live in poverty (there are disputes about the correct number, since there are disputes about the proper way to measure poverty). If everyone in Wisconsin thought of these children as their children, I doubt that we would find it tolerable. We would be less likely to think it is someone elses problem to solve or to donate a few canned goods to the local food pantry and be done with it. This, it seems to me, is the viable, contemporary take-way from Socrates communitarianism. Many readers will look upon the familial arrangements in the ideal polis with horror, regarding them as dystopic rather than utopic. But one can be a bit more community-minded and a bit less individualistic without following Socrates all the way. If thinking about the Second Wave leads readers to reflect on where they land on the communityindividual spectrum, and if that landing spot is where they think they ought to be landing, then we are doing what Plato really wants us to be doing: thinking for ourselves. We might find ourselves agreeing with Socrates that a life or culture too far to the individual side of the spectrum embodies a silly, adolescent idea of happiness (5.466b). Questions about the Ideal Polis 147 Having argued that converting the polis into one large household is beneficial, Socrates then starts to argue for its possibility. He focuses on warfare, which we will discuss briefly in a moment, but we might hope for more argument about whether dissolving the private family or household is psychologically possible for creatures like us. The worry is that Platos plan assumes that the intense affection parents typically feel for their children can be spread to all the children of the community. If this affection and instinct to protect ones offspring is a matter of biology, a cultural arrangement that does away with it might have trouble gaining traction. From a certain evolutionary perspective, parents love their children and seek to protect them because those children carry their DNA; we might well wonder whether this strong parental love can be extended to those with a different genetic make-up. While this is a question that Plato cannot be faulted for not answering, it is a question we might want an answer to as we reflect upon the meaning Platos proposal might have for us. Though Plato stressed human malleability in his account of education and enculturation, it is doubtful that humans are infinitely malleable, and our biology might put the brakes on his plan to household the polis, so to speak. There is more to be said about this, but for now we will just note it and move on to Socrates remarks on the ethics of warfare. Crucial to this discussion is a distinction between war ( [polemos]) and civil war or faction ( [stasis]). War occurs between parties that are naturally enemies, while faction occurs between natural friends. Greeks and non-Greeksbarbariansare natural enemies; non-Greeks are fundamentally different and other, being foreign and strange (5.470b). Greeks, by contrast, are ones own and akin (5.470b) and thus natural friends. Greekness does not seem to be a racial notion in the modern sense; Greeks are united by a shared language, cosmological mythology, and poetic tradition rather than biology. When Greek citystates fight each other, Socrates thinks, they should do so knowing that they will one day be reconciled. They should not, for example, burn houses or ravage fields. The trouble, as Plato sees it, is that Greeks fail to distinguish between Greeks and non-Greeks in warfare, fighting against each other the way they should fight only against non-Greeks. There is a moral distinction they need to make: they must treat barbarians the 148 Platos Republic: An Introduction way [they] currently treat each other (5.471b), and stop treating other Greeks as they currently do. We saw in the First Wave that, in the language of the PECI, sex was not a morally relevant difference that would justify giving unequal weights to the interests of men and women. Here, in the Second Wave, however, Socrates insists that race or ethnicity is morally relevant to the weighting of interests while engaging in warfare. The trouble, Socrates argues, is that Greeks are acting as though Greekness is not a morally relevant difference. They weigh the interests of Greeks and non-Greeks equally, but they should not be doing this: Greeks should give Greek interests greater weight than non-Greek interests, and thus change the ways in which they conduct the warfare that seems so inevitable in their world. It would be interesting to explore why for Plato race or ethnicity is a morally relevant difference while gender is not, but in the interest of moving forward we will set that issue aside and move on to the Third Wave. Some Suggestions for Further Reading Readers interested in the status of women and the nature of the family in classical Athens should see Sarah Pomeroy, Godesses, Whores, Wives, and Slaves: Women in Classical Antiquity (New York: Schocken Books, 1975) and Pomeroy, Families in Classical and Hellenistic Greece (New York: Oxford University Press, 1997). Plutarchs Sayings of Spartan Women can be found in Plutarch, Moralia, vol. 3, trans. by Frank Cole Babbitt (Cambridge, MA: Harvard University Press [Loeb Classical Library], 1931), pp. 45369. There has been much discussion of the question of Plato and feminism. Interested readers might start with Julia Annas, Platos Republic and Feminism, Philosophy, 51 (1976), 30721 (reprinted in Plato: Ethics, Politics, Religion, and the Soul, ed. by Gail Fine (New York: Oxford University Press, 1999) and C.D.C Reeve, The Naked Old Women in the Palaestra, in Platos Republic: Critical Essays, ed. by Richard Kraut (Lanham, MD: Rowman & Littlefield, 1997), pp. 12941, which is written as a dialogue. Questions about the Ideal Polis 149 Readers interested in the ethics of war might start with the Stanford Encyclopedia of Philosophy article by Seth Lazar (https://plato. stanford.edu/entries/war/), which gives an excellent overview and a full bibliography. Michael Walzer, Just and Unjust Wars: A Moral Argument with Historical Illustrations, 5th ed. (New York: Basic Books, 2015), is a contemporary classic. The philosophical literature on equality is vast, but Peter Singers Practical Ethics (New York: Cambridge University Press, 2011), https:// doi.org/10.1017/cbo9780511975950, is an excellent starting place. Though some of Singers views are controversial, he is philosophically astute and a very clear writer. John La Farge, The Relation of the Individual to the State: Socrates and His Friends Discuss The Republic, as in Platos Account; color study for mural (1903). Photograph by Pharos (2017), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/ File:The_Relation_of_the_Individual_to_the_State-_Socrates_and_ His_Friends_Discuss_%22The_Republic,%22_as_in_Plato%27s_ Account;_Color_Study_for_Mural,_Supreme_Court_Room,_Saint_ Paul,_Minnesota_State_Capitol,_Saint_Paul_MET_187194.jpg 8. Surfing the Third Wave: Platos Metaphysical Elevator, the Powers Argument, and the Infallibility of Knowledge, Book V Socrates regards the last of the Three Waves, whether it is possible for this constitution to come into being (5.471c), as the biggest and most difficult one (5.472a). The constitution he refers to is not a written document as in the US or even a collection of documents as in the UK; it is the conceptual organization of the ideal city itself. Constitution translates the Greek word (politeia, whence the English word politics), which is in fact the Greek title of the Republic. Socrates thinks that the ideal polis is indeed possible, but the condition of its being made real is as bold as it is famous and controversial: Until philosophers rule as kings or those who are now called kings and leading men genuinely and adequately philosophize, that is, until political power and philosophy entirely coincide, while the many natures who at present pursue either one exclusively are forcibly prevented from doing so, cities will have no rest from evils, Glaucon, nor, I think, will the human race. And, until this happens, the constitution we have been describing in theory will never be born to the fullest extent possible or see the light of the sun. It is because I saw how very paradoxical this statement would be that I hesitated to make it for so long, for it is hard Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.08 152 Platos Republic: An Introduction to face up to the fact that there can be no happiness, either public, or private, in any other city. (5.473ce) Glaucons reaction to Socrates inspirational little speech might not be what Socrates was hoping for: he thinks people will think that Socrates is either crazy or dangerous. So Socrates has his work cut out for him. Philosopher-Kings and Political Animals (5.471c474c) There is a lot going on in this famous paragraph. One crucial point is that political power and political wisdom are not merely separated in the non-ideal city that Socrates and company inhabit but are in fact at odds with each other. If those with political power lack political wisdom, they will lack the virtue necessary to perform well their function, governing. Even if those in power reject Thrasymachus self-interested conception of ruling and aim to act for the citys benefit rather than their own, they are likely to get things wrong as often as they get them right if they merely have beliefs about what is best for the city; what they need is knowledge. And those who possess this knowledgetrue philosophershave little interest in getting their hands dirty in politics, preferring a life of intellectual inquiry over political activity. Socrates thinks that this division between political power and political wisdom must be overcome, perhaps even by force, if the ideal city is to be made real. But the force in question will turn out to be the force of rational persuasion, rather than physical compulsion (thus reprising the force persuasion theme raised in the Republics opening scene.) Socrates doubles down on the importance of marrying political power and philosophy. Not only is their union the necessary condition for realizing this theoretical model of a good city (5.472e), but it is also required for human happiness itself: there can be no happiness, either public, or private, in any other city. It is this claim, Glaucon thinks, that people will find ridiculous or worse. But Socrates claim has more going for it than Glaucon first thinks. Socrates is suggesting that humans, being essentially social creatures, cannot fully flourish in defective cities or when living in Thoreau-like solitude. When Aristotle says early in his Politics that a human is by nature a political animal,1 he is not saying 1 Aristotle, Politics, I.2 1253a23. Surfing the Third Wave 153 that humans love to argue about politics or anything like that but rather that we are the kind of animal that lives in a polis, a view that Socrates surely agrees with. And many readers who are uncomfortable with Platos community-first ethos might find that their own conceptions of a good human life involve active engagement in a community, even if only one made up of their family and friends. Socrates will have something to say in Book VI about how one can live reasonably happily in an unjust and thus unhappy city, but only in a just city can a person fully flourish and be as happy as it is possible for a human being to be. Socrates solution to the Third Wave prompts the issue which will organize the remainder of Book V as well as Books VI and VII: we need to define [] who the philosophers are that we dare to say must rule (5.474b). This project of distinguishing philosopher from non-philosopher will take us into the deep end of the philosophical pool, so to speak, since the distinction will be twofold, drawing on Platos metaphysics (his account of the ultimate nature, structure, and constituents of reality, which will involve the famous theory of the Forms) and epistemology (his theory of knowledge). Metaphysics and epistemology are intimately related in Platos thought, as we will soon see when we examine the marquee argument of Book V, the Powers Argument. It is fair to say that this is the most intellectually challenging part of the Republic, but also the most intellectually rewarding, I think. Philosophers and Non-Philosophers The epistemological distinction between philosophers, who should govern, and non-philosophers, who should not, is that philosophers have knowledge of what is best for the city, while non-philosophers have belief or opinion ( [doxa, whence our word orthodoxy: correct belief]). Indeed, at the end of Book V, Socrates distinguishes between (philosophoi), lovers of wisdom, and (philodoxai), lovers of belief. We met the distinction between knowledge and belief back in Book IV, where it was put to use in explaining the cardinal virtues of wisdom and courage. The distinctive virtue of the guardian-rulers is wisdom, which is knowledge of what is best for the city as a whole. Courage, the distinctive virtue of the auxiliaries, is a matter not of knowledge but of beliefunshakably true belief about what 154 Platos Republic: An Introduction is appropriately feared, but something falling short of knowledge. An auxiliary will believe without doubt that dishonor and enslavement are worse than death, but they need not know why this is the case in order to perform their function well (although they may have true beliefs about why). Plato will have more to say about how knowledge differs from belief in Books VI and VII, especially in the analogies of the Divided Line and the Cave. For now, it is enough to note that the distinction is at the heart of Socrates response to the Third Wave: philosophers have knowledge while non-philosophers only have belief. The metaphysical distinction between philosopher and nonphilosopher will turn out to be intimately related to this first, epistemological distinction, since it is a distinction between the objects of knowledge and belief. The word metaphysics often conjures up thoughts of crystals, incense, New Age healing, etc., but this is not the philosophical sense. Philosophically speaking, metaphysics concerns the ultimate nature, structure, and constituents of reality. Where natural scientists try to discover and explain causal connections between events, metaphysically minded philosophers want to understand what causation itself is. They want to know what kinds of things exist: is everything that exists physical, or do non-physical things exist? For example, is the human mind something fully physical, reducible without remainder to the brain? Or is it something non-physical? If minds are non-physical, how do they interact with the body, which is decidedly physical? These are not the kinds of metaphysical questions that Plato asks; they assumed a central place in Western metaphysics with the thought of Ren Descartes (15961650). But hopefully they give the reader a sense of what sorts of concerns are addressed by metaphysics. We have beliefs about the particular things that make up our everyday world, on Platos view, but we have knowledge of the Forms the timeless essences of the particulars.2 A brief jump ahead to the beginning of Book X will be helpful in getting clearer about what the Forms are. There, Socrates reminds Glaucon that their usual procedure [] [is to] hypothesize a single Form in connection with each of the many things to which we apply the same name (10.596a). There must be something, Plato thinks, that all just 2 As is often done, I will use Form with a capital F when talking of these distinctively Platonic entities. Surfing the Third Wave 155 actions have in common, that all courageous actions have in common, that all red things have in common. Grasping this common featurethe essence or the Form, the real definitionis the task of philosophy, for Plato. His example in Book X is rather mundane: beds. The form, he says, is our term for the being of a bed (10.597a), where being means what the thing is: its essence, what it is to be a bed. So far, assuming a common feature seems like a reasonable, innocuous assumption. While there are many particular beds and many particular just actions, there is a single, unifying Form or essence of bedness and one of justice. So where particulars are many, Forms are one. Another crucial difference between Forms and particulars is that particulars are ever-changing. Of all the many beautiful things, Socrates asks, is there one that will not also appear ugly? Or is there any one of those just things that will not also appear unjust? Or one of those pious things that will not also appear impious? (5.479a) Although Plato does not share the subjectivist view that beauty is in the eye of the beholder, the beauty example is a helpful one. The sky to the west is beautiful right now, but in an hour, after the sun has set, it no longer is. Nor is it beautiful to my color-blind friend. The bouquet of flowers on the dining room table will not evoke oohs and ahs in two weeks. Thus, beauty seems both temporal and perspectival. As we saw in Book I, returning the weapon you have borrowed is usually just, but in a particular set of circumstances (say, its owner is deranged) it is not. Telling the truth is usually the right thing to do but sometimes the demands of kindness trump the demands of honesty. That fox seems big when standing next to the squirrel, but small when standing next to the bear. And so on. Being ever-changing and unstable are hallmarks of concrete particulars. Bob Dylan captures something of Platos point when he sings, He not busy born is busy dying. I hope my non-existence is a long way off in the future, but every day I live I am one day closer to my deathhence, I seem to be both living and dying, just as every beautiful thing seems both beautiful and not beautiful. The Forms are altogether different, on Platos view. Unlike the many particular beautiful things, the Form of beauty is permanent, stable, unchanging: the beautiful itself, Socrates says, remains always the same in all respects (5.479a). It is the only thing that is always and everywhere beautiful. The same goes for the Forms of justice, piety, redness, bigness, 156 Platos Republic: An Introduction whatever. While the world of particulars is in constant flux, the world of the Forms is stable and unchanging. We experience particular things and events via our senses, but the Forms are intelligible but not visible (6.507b): we perceive them with our minds, not our senses. One of Platos ways of referring to the Form of something drives this point home: the Form of a thing is the literally, the ideaof the thing. We cannot see or taste or touch or smell or hear ideas; we can only think them. But the word idea can be misleading, since for Plato the Forms are not psychological entities like thoughts or feelings, which depend for their existence on someone having them, as idea might suggest. Unlike ordinary thoughts and ideas, which cannot exist without thinkers thinking and having them, Platos Forms are mindindependently real, not depending for their existence upon thinkers thinking them. This is one of the most distinctive features of the Forms. It is one thing to claim that there is a common essence shared by particular things; it is another to claim that these common essences or Forms are not dependent, psychological entities but are instead mindindependently real. While the shadow my hand casts is real, it seems somehow less real than my hand, since its existence depends on the presence of the hand. Ideas and thoughts and feelings and moods seem similar to shadows in this regard: they are dependent entities, depending on conscious subjects for their existence. Plato does not deny this. But the Forms are not dependent psychological entities. It turns out that the Forms depend upon the Form of the goodgoodness itselfbut they are decisively unlike our ordinary ideas and thoughts. If this all sounds a bit weird, thinking about numbers can be helpful. Although the two coffee cups on the table are concrete particular objects, the number two is an abstract object, capable of being instantiated in space and time by infinitely many pairs of concrete particular objects but it is not itself a concrete particularat least on a plausible philosophy of mathematics known, perhaps unsurprisingly, as Platonism. One reason for thinking of mathematical objects as mind-independently real is that doing so helps us make sense of other beliefs many of us have about these objects. It will seem to many readers, for example, that the Pythagorean Theorem is timelessly true and would still be true even if no person ever thought of it. We should resist the temptation to say that numbers and the Forms Surfing the Third Wave 157 have always existed, because always existed is a temporal notion, and the idea here is that such entities are outside of time. Platos Metaphysical Elevator We can think of Platos metaphysics via the metaphor of an elevator, as in this diagram. Level 4 The Form of F is more real than the many particular Fs. Level 3 The Form of F is real: it is a non-spatiotemporal, mind-independent entity. Level 2 There is a form of F (the real definition of F), which all particular F things have in common. Level 1 The many particular F things are real: they are spatiotemporal, mind-independent entities. At Level One we find the everyday objects making up the world we experience through our five senses: trees, squirrels, rocks, picnic tables, etc. Most readers, I assume, think these objects are metaphysically real, existing independently of our minds and still there when we close our eyes or when we no longer exist. This is a plausible, commonsense 158 Platos Republic: An Introduction philosophical view, though of course not all philosophers hold it. The great Irish philosopher George Berkeley (16851753), for one, thought that what we ordinarily take to be mind-independently real things are in reality mind-dependent ideas. We are tempted to think of them as mind-independently real because they seem to persist in our absence, but, he thought, this is only because God continues to think them when we do not. Berkeleys motto was esse est percipi: to exist is to be perceived. This seems right for headaches, for example, which require someone to perceive them; they are not floating around in space, waiting to land on an unfortunate victim. So while some philosophers will not even get on Platos elevator at the first floor, most of us will. At Level Two we find those real definitions or essences that Socrates is forever seeking, the trait or property that all F things have in common: chairness, justice itself, etc. Most readers, I suspect, will take Platos elevator to Level Two. We think that the many particular things we experience through our senses come in clusters unified by common properties: there are red things, round things, beautiful things, just and unjust actions and social arrangements, etc. Ascending to Level Two results from agreeing with Socrates that there is a single form in connection with each of the many things to which we apply the same name (10.596a). Indeed, the Republic is the search for the Form of justice, as many of Platos dialogues are searches for the Forms or essences of various virtues such as piety, courage, temperance, etc. But at level two, we find forms, rather than Forms, since they are not mindindependently real, existing in their own right. Not everyone will follow Plato to Level Two, however. The great twentieth-century philosopher Ludwig Wittgenstein (18891951), for one, declined the invitation, thinking that the search for one commonality was misguided and inevitably futile. If we consider the wide variety of gamescard games, board games, ball games, party games, computer games, etc.we will see, Wittgenstein thought, that there need not be features common to everything we call a game: Or is there always winning and losing, or competition between players? Think of solitaire. In ball games there is winning and losing; but when a child throws his ball at the wall and catches it again, this feature has disappeared [] Think now of games like ring-a-ring-a-roses; here is the element of amusement, but how many other characteristic features have Surfing the Third Wave 159 disappeared! And we can go through the many, many other groups of games in the same way; can see how similarities crop up and disappear.3 Instead of an essence shared by all games, Wittgenstein finds a complicated network of similarities overlapping and crisscrossing, which he dubs a family resemblance. Not everyone accepts Wittgensteins view; Bernard Suits, for one, thought he had found the essence of game. But it is worth noting that contemporary psychology and cognitive science seem to side with Wittgenstein over Plato. According to prototype theory, first articulated by the cognitive psychologist Eleanor Rosch in the early 1970s, our concept of, say, bird, involves a cluster of features, some more important than others, with certain examples serving as prototypes.4 If you want to give someone an example of a bird, you are likelier to offer a robin or cardinal as an example than you are to offer a penguin, because penguins lack one of the prototypicalbut not necessarytraits of we associate with birds, namely the ability to fly. Even though Wittgenstein would not ascend to Level Two, preferring family resemblances to essences, many readers will follow Socrates there. It is at Level Three, though, where Platonism really starts to kick in, for Level Three involves a commitment to the real, mind-independent existence of these Forms or common properties. At Level Three, we discover essences and Forms; we do not invent them. It is one thing to regard the Form or essence of justice or kindness or chairness as a psychological entity, a conceptual construct having no mind-independent existence in its own right. It is another thing entirely to regard the Form as mind-independently real, something that is to be discovered rather than invented. You can ascend to Level Two while thinking that the Forms are like ordinary ideas and thoughts, not real in themselves but rather depending for their existence on thinkers thinking them. But ascending from Level Two to Level Three requires a considerable jump in what philosophers call ontological commitment, a fancy-sounding but precise phrase indicating which kinds of things one is prepared to say exist in their own right. Few people, for example, are ontologically committed to unicorns or the tooth fairy: most of us do not regard 3 Ludwig Wittgenstein, Philosophical Investigations, 3rd. ed., trans. by G. E. M. Anscombe (Oxford: Basil Blackwell, 1973), 66, p. 32. 4 Eleanor Rosch, Natural categories, Cognitive Psychology, 4 (1973), 32850. 160 Platos Republic: An Introduction them as mind-independently real. And while most of us think that our thoughts and feelings are real in an everyday sensethe sense which contrasts real with imaginary or hallucinatorywe do not regard them as real in the sense of existing in their own right, mind-independently. Many people who find the ascent to Level Two unproblematic and obvious will balk at ascending to Level Three. Why go there, after all? It seems needlessly complicated or metaphysically profligate to posit the real, mind-independent existence of Socrates real definitions. Many readers are familiar with Ockhams Razor, which in one formulation tells us that the simplest explanation of a phenomenon is usually correct. Perhaps less familiar is the ontological formulation of the Razor, which bids us not to multiply entities beyond necessity: non sunt multiplicanda entia sine necessitate. In short, if you do not need to posit the existence of certain things or kinds to make sense of your experience, then dont; be metaphysically frugal and parsimonious. No doubt this metaphysical or ontological simplicity is related to explanatory simplicity: explanations involving fewer kinds of entities will probably be simpler. It is as though there is an ontology tax that philosophers are keen to avoid paying. Most of us find ontological commitment to ships and shoes and sealing wax unproblematic because it is difficult to make sense of our everyday experiences without a commitment to the real existence of the spatiotemporal objects that we sit on, stub our toes on, eat, etc. But many readers will resist ontological realism about Platos Forms, feeling they can understand and explain their experiences without appeal to them. The journalist Hunter S. Thompson once wrote, When the going gets weird, the weird turn pro.5 If so, then Level Four is where one loses ones amateur standing. For those ascending to Level Four go beyond ontological commitment to the real, mind-independent existence of the Forms that typified Level Three. On Level Four, the Forms are not merely mind-independently real but are more real than the spatiotemporal particulars that are instances of them. The idea that the essence of chairness is more real than the chair one is sitting on is, well, pretty weird. Many people will get off the Platonic elevator at Level Two, being 5 Hunter S. Thompson, The Great Shark Hunt: Strange Tales from a Strange Time (New York: Simon & Schuster, 1979), p. 36. Surfing the Third Wave 161 philosophically unwilling, perhaps for Ockham-inspired reasons, to ascend to Level Three. But of those who go to Level Three, few, I suspect, will be willing to go all the way to Level Four, and readers might be forgiven for thinking that Socrates has gotten into the drugs reserved for the rulers of the city (5.459c). Butbad jokes aside: the drugs are not those kinds of drugs, anywayhis reasons for ascending to Levels Three and Four are philosophical rather than psychedelic, and it is to those philosophical reasons that we now turn. Marrying Metaphysics and Epistemology: The Powers Argument (5.476d480a) The metaphysical and epistemological distinctions are intimately related, for Plato. In what I call the Powers Argument, he starts with epistemology and ends up at metaphysics, arguing that the distinction between knowledge and belief requires allegiance to the Forms, since knowledge and belief, being different powers, must have distinct kinds of objects. The Powers Argument is crucial to addressing the Third Wave, since it will help define [] who the philosophers are that we dare to say must rule (5.474b), but its implications go beyond this, as it attempts to give good reasons to ride the Metaphysical Elevator all the way up. The epistemological and metaphysical distinctions fit together this way: concrete particular things are the objects of belief, while the Forms are the objects of knowledge. A non-philosopher has beliefs about the many particular things and activities that make up the furniture of our everyday world: chairs, just actions, cats, sunsets. They believe[] in beautiful things, but do[] not believe in the beautiful itself (5.476c). The philosopher, by contrast, is able to see and embrace the nature of the beautiful itself (5.476b), the Form or essence in virtue of which all particular beautiful things are beautiful. A non-philosopher can have a true belief that a sunset is beautiful but never knowledge of this. Indeed, there is no knowledge of such things (7.529b), as the Forms and not particulars are the proper objects of knowledge, on Platos view. But perhaps something that falls short of knowledge but is more than true beliefknowledge with an asteriskis possible where particulars are concerned. If so, a philosopher might know* that this particular sunset 162 Platos Republic: An Introduction or that particular painting is beautiful by grasping the Form of beauty and seeing that the painting or sunset is an instance ofparticipates in, as Plato often puts itthe Form, if only temporarily. Such a philosopher would know why the sunset is beautiful, which is beyond the cognitive capacities of a non-philosopher, who lacks access to the Form of beauty and thus never ascends above true belief. The Powers Arguments crucial concept, which gives it its name, is the concept of a power ( [dunamis, whence the word dynamic]). Sight, hearing, touch, taste, and smell are ordinary examples of powers, which we might also call capacities or faculties. Animals typically have the power of sight; rocks do not. Even though powers are what enable us to see, hear, touch, taste, and smell the world, powers themselves are not the kinds of things we can see, hear, touch, taste, and smell. We distinguish them, Socrates says, by what they do and what they are set over (5.477d)by their functions and their objects: What is set over the same things and does the same I call the same power; what is set over something different and does something different I call a different one (5.477d). Talk of knowledge and belief as powers, analogous to sight and hearing, might make this first premise sound odd to modern ears, but this is how Socrates conceives of them. The second premise is the claim that knowledge and belief are different powers, which Glaucon regards as obviously true to a person with any understanding (5.477e). From these two premises Socrates concludes that knowledge and belief must have different objects. This conclusion seems innocuous enough, but we will soon see that it is anything but. Having established, he thinks, that knowledge and belief must have different objects, Socrates then tries to determine what these different objects are. Knowledges object, Glaucon agrees, is what is (5.478a). There is a trifold ambiguity here that we should be aware of. In the existential sense, what is means what exists, what is real. Someone who asks, Is there a god?, is using is in the existential sense. In the epistemic sense, what is means what is true, what is the case. News anchor Walter Cronkites signature sign-off, And thats the way it is, employed is in the epistemic sense. In the predicative sense, is serves to link subject and predicate: the sky is blue, Jonas Starker is a great cellist, etc. So what Surfing the Third Wave 163 is means what is , where the dots are filled in with some predicate: what is red, what is beautiful, what is just, etc. Plato does not make explicit which sense of is Glaucon has in mind when he says that knowledges object is what is. To get a sense of the argument without becoming ensnared in scholarly controversy, I propose that we read what is in the existential sense, given the metaphysical implications of the argument. Taken this way, when Socrates says that knowledge is set over what is (5.478a), he is saying that the objects of knowledgewhat we know when we know somethingexist: they are real. And the Forms exist, so they are objects of knowledge. Ignorance, by contrast, has as its object what is not (5.477a, 478c): what does not exist. (It is odd to think of ignorance as a power or capacity, since it does not enable its possessor to do anything, as powers usually do, but let us set aside this minor point.) Since belief is in between knowledge and ignorance, darker than knowledge but clearer than ignorance (5.478c), its objects will be intermediate between what is and what is not. Thus the objects of belief participate in both being and not-being (5.478e): they straddle both existence and nonexistence, not fully real but not unreal, either. In short, the objects of belief are the particulars of everyday experience. To summarize: knowledge and belief, being different powers, must have different objects. Indeed, they have very different kinds of objects: knowledges objects are the timeless Forms, while beliefs objects are the spatiotemporal particulars that make up our everyday world. So there are two metaphysically different worlds: the world of the Forms and the world of particulars. The world of the Forms is the world of reality while the world of particulars is the world of appearancebut not, I hasten to add, a world of illusion. Plato is very careful with his language here, emphasizing that those things we think of as being beautiful really only appear beautiful, since they also appear ugly. Is there any one of those just things, Socrates asks, that will not also appear unjust? Or one of those pious things that will not also appear impious? (5.479a) Plato is not claiming that our everyday world is illusory in the sense of not being real. It is just not as real as the world of the Forms. It is smack dab in the middle, metaphysically, more real than complete non-existence, but less real than complete existence. 164 Platos Republic: An Introduction Problems with the Powers Argument That is a lot to take in, so let us pause and restate the argument in premise-conclusion form, in order to grasp its structure more clearly, which should help us analyze it: P1 x and y are the same power if and only if (a) x and y have the same objects and (b) x and y have the same function. (5.477d) P2 Knowledge and belief are different powers. (5.477b,e) C1 So, knowledge and belief have different objects and different functions. (5.478a) C2 So, knowledge and belief have different objects. P3 Knowledges object is what is. (5.478a,c) P4 Belief is intermediate between knowledge and ignorance. (5.478d) P5 Ignorances object is what is not. (5.478c) C3 So, beliefs object is what is and what is not. (5.478d) (A minor detail regarding C1: Grubes translation does not quite square with the Greek text here, which is better captured by C2which logically follows from C1. I do not think anything rides on Grubes addition, but some readers, especially brave souls wrestling with the Greek text, will want to know this.) Let us work backwards, starting with C3. We have already noted that for Plato particular things are bundles of opposites, simultaneously beautiful and not beautiful, just and not just, etc.: each of them always participates in both opposites (5.479b). But Socrates now takes this to imply that these particular things are intermediates between what is not and what purely is (5.479d). This is something new. It is one thing to claim that predicates like is beautiful both apply and do not apply to one and the same particular objectthat the particular thing participates in both beauty and non-beauty. But why would this imply that any particular participates in both being and nonbeing (5.478d), that it somehow both exists and does not exist? There seems to be something a little fishy here. Socrates seems to slide from Surfing the Third Wave 165 the predicative sense of is, where it links subjects and predicates, to its existential, existence-asserting sense. That is, he seems to slide from (Predicative) Any particular thing both is beautiful and is not beautiful to (Existential) Any particular thing both is and is not, as if he simply crossed out the occurrences of beautiful in (Predicative). Bertrand Russell once wrote that employing the same word to express such different senses was a disgrace to the human race.6 Russells hyperbole is no doubt tongue-in-cheek, but there is a serious point in the background: philosophy often requires attention to linguistic subtleties like the distinction between the senses of is. In this portion of the argument, Socrates seems to elide the distinction between the predicative and existential senses, drawing a conclusion employing the latter from a premise employing the former. I stress that he seems to me to be doing this; I am not insisting that he actually does so. Such insistence would violate the principle of charity, which requires us to interpret texts and utterances in ways that maximize their truth and reasonableness and logical validity. But sometimes even very smart people make logical blunders, and the principle of charity does not require us to pretend otherwise. If this were a different book, aimed at a different audience, we would explore this question in depth and detail. Some people are sufficiently fascinated by issues like this as to become Plato scholars, and no doubt some of those scholars are rolling their eyes or at least arching their eyebrows at what I have said here. Butand here I am on firm logical groundthis is not a different book than it is, so I tentatively suggest that we view this apparent equivocation between senses of is as a heuristic device to help us think critically about the argument and move on. These concerns about whether Socrates makes this predicative-toexistential slide fade into the background when we see how problematic the first part of the argument is, the derivation of C1 from P1 and P2. Glaucon thinks that C1 necessarily (5.478a) follows from P1 and P2, 6 Bertrand Russell, Introduction to Mathematical Philosophy (New York: MacMillan, 1919), p. 172. 166 Platos Republic: An Introduction but his confidence is misplaced, since the conclusion does not follow necessarily at all. Since the conclusion could still be false even if we assume that the premises are true, the argument is invalid. To see this, consider a parallel example. Two Constitutional conditions of eligibility to be President of the United States are (a) that one be at least thirty-five years old and (b) that one be a natural-born citizen. From the fact that my friend Geoff is not eligible to be President, it does not follow that he is not at least thirty-five and that he is not a natural born citizen; what follows is that either Geoff is not at least thirty-five years old or Geoff is not a natural-born citizen. Both negative conclusions might follow, as they do in the case for my cat Frobisher, who, despite having been born here, is not a citizen of the US and is well shy of thirty-five. But all we and Socratesare entitled to is the or. If I know that Geoff is well past thirty-five, I can then conclude that he is not a natural-born citizen (he is, in fact, Canadian). But until I know that, I am jumping to a conclusion I am not entitled to draw. What Socrates should conclude from P1 and P2 is that either knowledge and belief have different objects or they have different tasks. It might be that both their objects and tasks differ, but Socrates is not entitled to conclude that. To get to C2, the conclusion that knowledge and belief have different objects, from C1, which now functions as the premise that they either have different tasks or different objects, he has to show that knowledge and belief do not have different tasks. But without doing this, he is jumping to a conclusionC2that he is not entitled to. So Plato, in the person of Socrates, has committed one of the gravest of philosophical sins: he has given a logically invalid argument. But even if we could fix the logical invalidity, switching the and in C1 to an or, it is difficult to see how Socrates can get to C2. Powers differ more often by having different tasks or functions than by having different objects. Shepherds and butchers, for example, share a common object, sheep, but they have different tasks in relation to that object: shepherds seek to nurture sheep while butchers seek to turn them into lamb chops. On a common conception of education (though one we will see Plato calling into question in Book VII), teaching and learning have the same object, knowledge, but have different tasks or functions with respect to that object: teaching seeks to impart or instill knowledge while learning seeks to acquire it. And so on. Surfing the Third Wave 167 Perhaps the trouble is thinking of knowledge and belief as powers or capacities. Plato thinks that each of the senses has a distinct object: sights object is color, hearings is sound, etc. In the Theaetetus, a dialogue roughly contemporary with the Republic, Socrates says, what you perceive through one power, you cannot perceive through another (185a). Cases of synesthesia aside, this has the ring of truth, though it seems to have the odd implication that we cannot see and smell and taste the same object, when it seems clear that we can: I see the coffee, smell it, taste it, etc. But Socrates could respond that we see the coffees color, smell its aroma, feel its heat, etc. These various sensations are synthesized or integrated into a unified sensory impression, but the various senses are modular, operating independently. We perceive the coffee by or through perceiving its sensible qualities. But, a critic might insist, it is not the case that these powers ultimately have different objects; instead, they have a common object: the coffee. It is true that their intermediary objects are different properties or qualities of that objectwe see color, smell aroma, etc.but there is a common object that those various sensory qualities belong to. So we have reason to be skeptical of the first premise of the Powers Argument. And even if we give Socrates the benefit of the doubt and take him to be talking of the various intermediate objects of these powers, not the ultimate object, we might wonder what reason we have to think of knowledge and belief as analogous to powers in having unique objects. Most contemporary philosophers would agree with the spirit of P2, since they think that knowledge and belief are different cognitive or epistemic states, though they would be unlikely to think of them as powers. Few, though, would agree with Platos conclusion that knowledge and belief have different kinds of objects. As discussed earlier, on the JTB (Justified True Belief) conception of knowledge, to know something is to have a belief that is not only true but is also justified, which (on a plausible account of what it is to be justified in believing something) requires good reasons for having the belief. Most contemporary philosophers would regard C2 as false, since knowledge and belief, though different, have the same objects: propositions. In the first sentence of the Gettysburg Address, Lincoln speaks of the Founders dedication to the proposition that all men are created equal. If he had said it in French (la proposition que tous les hommes sont crs 168 Platos Republic: An Introduction gaux) he would have expressed the same proposition. Even though we express propositions in language, at heart propositions are conceptual entities rather than linguistic ones, and the same proposition can be expressed in different languages. Lincoln believed in the proposition of fundamental human equality, while Plato, we have seen, did not. Both Anna, who grew up in Wisconsin and has looked at her share of roadmaps and atlases, and Bryce, a Coastie with a vague picture of the geography of North America who has trouble locating Wisconsin on a map (for him the Midwest is a vague blobject), believe the proposition that Wisconsin is east of the Mississippi River. On the JTB conception, Anna knows this while Bryce does not. Though Bryces belief is true, he does not have good reasons for it, since when pressed the only reason he offers is, I just think it is. Though Anna and Bryce are in different cognitive and epistemic states, their objects are the same, the proposition that Wisconsin is east of the Mississippi River. Or so say most contemporary epistemologists. That most contemporary philosophers think C2 is false does not make it false, of course, but in the next section we will see reason to think they are probably right about this. Platos Fallible Conception of Infallibility So why does Plato have someone as smart as Socrates make such a logically flawed argument? It may be that the argument accurately reflects Socrates reasoning, which Plato faithfully reproduces, though that seems unlikely. Perhaps this is one of those instances of Platos intentionally having Socrates make a bad argument in hopes of engaging the reader in philosophical dialogue, since the yes-men Socrates is talking with do not seem up to the task. That is certainly possible, but here it does not ring trueat least to me. In those instances in Book I when the bad arguments seem intentionale.g., in Socrates first refutation of Polemarchusthere was a substantive philosophical point that Plato seemed to want his readers to work out for themselves (that virtues are not crafts or skills). But given how much is at stake herereasons for believing in Platos Forms, for taking Platos Elevator to the Third and Fourth Levelsit is an odd time for such a lesson. Perhaps Plato has independent reasons for believing C2, that knowledge and belief have Surfing the Third Wave 169 different objects, and this makes him less attentive than he should be to the quality of the reasons he offers here in support of this belief. It is a common enough human failing, but it is surprising to see Plato falling victim to it here. Those independent reasons for thinking C2 is true can be found in the discussion Socrates and Glaucon have about P2. Glaucon agreesas we all shouldthat knowledge and belief are different. How could a person with any understanding, he asks, think that a fallible power is the same as an infallible one? (5.477e) The idea that belief is fallible should ring true: we regularly believe things that are not true. We think they are true, of course, and sometimes insist that they are. After all, we probably would not believe them if we knew they were false, since to believe something is, at least in part, to take it to be true. But while I can believe things that are false, I cannot know things that are false. I might believe that Orson Welles directed The Third Man or that Edward Albee wrote Desert Solitaire, but I cannot know these things, since they are false. On the JTB conception, remember, my beliefs count as knowledge only if they are true (though being true is not enough: those true beliefs also have to be justified). For contemporary philosophers, that is the sense in which knowledge is infallible and belief is fallible: I can believe things that are false but I cannot know things that are false. Plato seems to have a different understanding of the infallibility of knowledge, one that goes beyond the view that we cannot know things that are false and holds that we cannot know things that could be false. In other words, the objects of knowledge must not only be true, they must be necessarily true. While a contingent truth could be false, a necessary truth cannot possibly be false: it must be true. The candidates for such things are few, but the truths of mathematics offer the most intuitively plausible examples of necessary truths. Although it is not completely uncontroversial, I think that the Pythagorean Theorem is necessarily true, that it was true even before anyone thought of it and would be true even if no one ever thought of it, even if no creatures capable of understanding geometry had ever existed. That the square of the hypotenuse of a right triangle is equal to the sum of the squares of the other two sides is not merely a mind-independent truth, it is a mindindependent truth that could not be false. Given the nature of right triangles, there is no way the square of the hypotenuse could not equal 170 Platos Republic: An Introduction the sum of the squares of the other two sides. If there are two mittens and one stocking cap on the table, it is mind-independently true there are three things on the table: it does not matter whether I am looking at them or not; there are three things on the table. But it is merely a contingent truth that there are three things on the table; I could have just as easily kept my stocking cap on (it is cold in here!), in which case there would only be two items on the table. So while it is true that there are three items on the table, it is a contingent truth. But that three is the sum of one and two is a necessary truth: it cannot be otherwise. And here it is important not to confuse numbers with numerals, which are our names for numbers. We could use the word two to name the number three and the word three to name the number twoheck, we could call two Ethel and three Fred. The English sentence two plus one is three is only contingently true, since which words attach to which objects is a contingent fact of English. But the proposition it expresses, that the sum of two and one is three, is necessarily true, regardless of which names or numerals we use to designate the numbers. The crucial difference between these two conceptions of the infallibility of knowledge is that the contemporary conception of infallibility is a claim about the nature of knowledge, while for Plato it is a claim about the objects of knowledge: Contemporary: Necessarily, if someone knows that p, then p is true. Plato: If someone knows that p, then p is necessarily true. A lot rides on where necessarily appearsor as linguists and philosophers would say, on its scope. There is a world of difference between Not Trying I am not trying to hear what they are saying and Trying Not I am trying not to hear what they are saying. Not Trying is true so long as I am not making an effort to hear what they are saying (e.g., I am not leaning in, putting my ear to the wall, etc.); if I hear what they are saying, perhaps the fault is theirs and not mine, since I was not eavesdropping. But Trying Not requires that I make an effort to not hear them (e.g., I cover my ears, change locations, etc.).; Surfing the Third Wave 171 if I hear what they are saying, I have failed in my attempt to not hear themperhaps I should have tried harder. Similarly, the difference between the contemporary and Platonic conceptions of the infallibility of knowledge is a difference in the scope of the adverb necessarily. On the contemporary account, what is necessarily true is a claim about the nature of knowledge, that if I know that p, then p is trueso I can have knowledge only of things that are true. On the account I am attributing to Plato, it is the proposition known that is necessarily true: if I know that p, then p is necessarily trueso I can have knowledge only of necessary truths, never of merely contingent truths. If Plato understands the infallibility of knowledge as I have suggested, it is no wonder that he thinks that knowledge and belief must have different objects. Only the Forms, Plato thinks, have the necessity required of objects of knowledge, since only the Form of beauty is completely beautiful; particular beautiful things are too awash in contingency and opposition to make the grade. (The self-predication of the Formsthe view that the Form of beauty is beautiful, the Form of justice is justis of great interest to Plato scholars, but it is an issue we need not tangle with here. Suffice it to say that there are problems with this view: if the Forms are self-predicating, then the Form of beauty is beautiful and the Form of justice is just. That might seem just fine, but then the Form of bigness is big and the Form of smallness is small, the Form of redness is red and the Form of squareness is squareall of which are odd implications for entities that are not spatiotemporal.) Most of the truths of our everyday livesour names, where we parked the car, our favorite flavor of ice cream, how many (if any) children we haveare contingent truths, not necessary truths: they could have been otherwise. My parents could have named me Ivan instead of Sean; I parked the car in the street but I could have parked it in the driveway or in the garage, etc. Things could be different than they are. On the ordinary conception of knowledge, I know that my name is Sean and that I have two cats. But on the stronger understanding of the infallibility of knowledge that Plato seems to have, I do not know these things, since they are only contingently and not necessarily true and thus not proper objects of knowledge. This will strike many readers as quite counter-intuitive; most of us feel quite confident that we know our 172 Platos Republic: An Introduction names (though where we parked the car might be a different matter entirely, especially for garageless city-dwellers). So it is plausible that Platos view about the infallibility of knowledge is what accounts for his belief that knowledge and belief must have different objects. And it might help explain why he does not seem aware of the weaknesses of the actual argument he gives to support that belief. But there are still the facts that the Powers Argument is logically invalid and its key first premise is false. It is certainly the marquee argument of Book V, intended to provide good reasons to accept Platos distinctive metaphysics. Of course, Platos metaphysics might still be correct: the conclusion of an invalid argument can still be true. But as things stand, there is a gaping hole in the middle of the Republic. Some Suggestions for Further Reading Readers looking for an excellent introduction to metaphysics by one of the best contemporary philosophers will find it in Peter Van Inwagen, Metaphysics (4th ed.) (Boulder: Westview Press, 2014). Readers interested in a good, brief introduction to epistemology should see Jennifer Nagel, Knowledge: A Very Short Introduction (New York: Oxford University Press, 2014), https://doi.org/10.1093/ actrade/9780199661268.001.0001. For an overview of Platos metaphysics and epistemology, interested readers should see Allan Silverman, Platos Middle Period Metaphysics and Epistemology, in the ever-helpful Stanford Encyclopedia of Philosophy (https://plato.stanford.edu/entries/plato-metaphysics/). For an advanced discussion of some of the issues treated in this chapter, interested readers might start with Gail Fine, Knowledge and Belief in Republic V, in Plato 1: Metaphysics and Epistemology, ed. by Gail Fine (New York: Oxford University Press, 2000), pp. 21546. Gregory Vlastos, A Metaphysical Paradox, in Platos Republic: Critical Essays, ed. by Richard Kraut (Lanham, MD: Rowman & Littlefield, 1997), pp. 18195, is an accessible discussion of Platos two-worlds metaphysics by one of the twentieth centurys leading Plato scholars. Surfing the Third Wave 173 For readers interested in Wittgensteins philosophy, his Philosophical Investigations, 3rd ed., trans. by G. E. M. Anscombe (Oxford: Basil Blackwell, 1973) is a good place to start. Bernard Suits, The Grasshopper: Games, Life, and Utopia, 3rd ed. (Peterborough, ON: Broadview Press, 2014) is of great interest in itself and also for its anti-Wittgensteinian analysis of the concept of a game. Readers interested in Berkeleys philosophy might start with George Berkeley, Principles of Human Knowledge and Three Dialogues Between Hylas and Philonous, ed. by Roger Woolhouse (Harmondsworth: Penguin Classics, 1988). Jonathan Bennetts helpful modernization can be found at Early Modern Texts (http://www.earlymoderntexts.com/). Readers interested in the philosophy of mathematics might start with Stewart Shapiro, Thinking about Mathematics: The Philosophy of Mathematics (New York: Oxford University Press, 2000). Philosophy of Mathematics: Selected Readings, ed. by Paul Benacerraf and Hilary Putnam, 2nd ed. (Princeton: Princeton University Press, 1983) is a classic collection of essays on this fascinating and difficult area of philosophy. Platos Theaetetus is a Socratic dialogue especially focused on epistemology. The Parmenides explores the complexities of the theory of the Forms, among other things. There are excellent translations of both in Plato: Complete Works, ed. by John Cooper (Indianapolis: Hackett Publishing, 1997). Hackett also offers stand-alone translations along with informative, detailed introductions. B-side of bell krater with scene of three young men with himatia in an arena. Photograph by ngel M. Felicsimo (2016), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/File:Cr%C3%A1tera_ (38877852382).jpg 9. The Philosophers Virtues: Book VI Although there are serious problems with the Powers Argument, its invalidity and unsoundness do not entail that the ideal city will get washed away by the Third Wave. For even if we reject the mind-independent reality of the Forms or, more cautiously, regard belief in their mindindependence as unjustified, we can still agree with Plato that ideal rulers will possess knowledge of what is best for the city. Although the distinction between knowledge and belief is crucial to Platos distinction between philosopher and non-philosopher, knowledge and belief can be different epistemic states even if they do not have different objects. So the distinction between knowledge and belief, and the distinction between philosopher and non-philosopher that it underlies, can survive the failures of the Powers Argument, since the distinction itself does not depend on Platos particular way of making it. In this chapter, we will look at another way in which Plato tries to distinguish between a true philosopher and [] a counterfeit one (6.485d). He is especially keen to distinguish genuine philosophers from sophists, the professional teachers of rhetoric whom the public mistakenly takes to be philosophers. In doing so, Plato will not only shore up his response to the Third Wave by further defin[ing] who the philosophers are that we dare to say must rule (5.474b), but he will also exonerate Socrates, who, as many readers know, was tried and convicted of impiety and corrupting the youth of Athens and put to death for those alleged crimes in bce 399. Sophists, and not philosophers, Plato insists, are guilty of corrupting the youth (6.492a). In a phrase that will recall Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.09 176 Platos Republic: An Introduction his Book I exchange with Thrasymachus, Socrates wants to discover who the philosophers are in the most exact sense of the term (6.503b). In asking whether a soul is philosophic or not (6.486b), Plato indicates that being a philosopher is a matter of nature as well as nurture. All the education and nurture in the world will not produce a philosopher if the underlying philosophic nature is not present, and improperly educating someone with a philosophic nature will not just fail to produce a philosopher, it is likely to produce moral depravity: the best natures become outstandingly bad when they receive a bad upbringing (6.491e). Those who naturally possess the intellectual wherewithal to be philosophers but who do not receive the right kind of education can do far more harm than their less intellectually endowed fellows. Plato seems to have in mind here the historical Alcibiades, a beautiful, brilliant young Athenian who proved a traitor, switching sides to Sparta in the Peloponnesian War. Fans of the television drama Breaking Bad will not be far off the mark in taking Walter White as an example of Platos point, since his intellectual prowess makes him far worse, morally, than his partner and former student, Jesse. Socrates task is to describe the philosophic nature, to show what philosophers are like in contrast with non-philosophers. In Book VII he will discuss their nurture, expanding on the program of education already spelled out in Books II and III. In Book V the distinction between philosopher and non-philosopher rested on the distinction between knowledge and belief, which led us to the metaphysical distinction between Forms and particulars. Here the focus is on the virtues that true philosophers can and do possess. Loving the Truth The most important of these virtues is love for the truth. Not only must philosophers be without falsehood, they must refuse to accept what is false, hate it, and have a love for the truth (6.485c). This will strike many readers as surprising in light of Socrates earlier insistence that the rulers will have to employ falsehood in governing, for example in rigging the lotteries determining the sacred marriages. In addressing the Second Wave, Socrates conceded that our rulers will have to make considerable use of falsehood and deception for the benefit of those The Philosophers Virtues 177 they rule (5.459c). Is Plato being inconsistent here? It may look that way at first, but on closer examination it seems not. After all, rulers can employ falsehoods even though they hate them and reluctantly use them only when something important is at stake, when the falsehood is beneficial to those it is being told to, and when it is the only or perhaps the most effective means to bringing about the benefit. And the distinction between true or genuine falsehoods and merely verbal falsehoods, which we met toward the end of Book II, blunts the charge of inconsistency as well. While rulers will find employing verbal falsehoods useful, presumably they will never employ the radically false and soul-distorting true or genuine falsehoods. The rulers can hate what is most truly or genuinely false but reluctantly employ mere verbal falsehoods, which are useful and so not deserving of hatred (2.382c). Verbal falsehoods are like medicine (2.382c, 3.389b), after all, and medical treatment is one of Glaucons main examples of goods that are onerous but beneficial (2.357c), not intrinsically desirable (and perhaps intrinsically undesirable) but useful. While there may be a tension in Platos view, upon reflection it seems to fall far short of inconsistency. That this crucial philosophical virtue involves love should not be surprising, given the centrality of truth to the philosophical enterprise and indeed that philosophy is, etymologically, the love (philein) of wisdom (sophia). Love of truth pairs well with the role played by the guardian-rulers love for the city back in Book III, which Socrates reminds us of here in Book VI: the rulers must be lovers of their city ( [philopolis]) (6.503a). We noted earlier Platos playing up the cognitive dimension of love, focusing on the lovers belief that their beloveds flourishing is an essential part of their own flourishing. This is not to say that their love is merely cognitive, involving no feelings for the beloved or commitment to it. Perhaps Plato focuses on loves cognitive dimension because its affective dimensionhow it feelsis so obvious and potent that it is likely to lead us to think of love as exclusively a matter of feeling. Plato, committed as he is to the centrality of reason in a well-lived life, wishes to remedy this by highlighting loves rational, cognitive side. Back in Book III Socrates claimed that the right kind of love ( [ho orthos ers]) has nothing mad or licentious about it and instead is the love of order 178 Platos Republic: An Introduction and beauty that has been moderated by education (3.403a). Although we tend to think of erserotic or romantic lovein terms of sexual passion, Plato argues in the Symposium that its proper object is the Form of or essence of beauty. The goal of the musical education, after all, is love of the fine and beautiful (3.403c). The love philosophers have and feel for the truth is (stergein) rather than or , but perhaps we should not read too much into this, as Plato does not here draw hard-and-fast distinctions between kinds of love as later authors are wont to do, e.g., between philia, eros, and agap (friendly love, erotic or romantic love, and neighborly love). But it is telling that stergein typically refers to parental love, which clearly involves the parents identifying their childs wellbeing with their own, and which involves a distinctive kind of affection. Love of truth may well be the Socratic virtue par excellence, though when we first meet Thrasymachus, he insists that Socrates is (philotimos), a lover of honor and victory (rather than truth) who just wants to win arguments. This seems an ironic projection on Thrasymachus part, since he aims to persuade his audience of a predetermined conclusion by the power of his rhetorical skill, rather than to investigate the matter and accept whatever conclusions reason leads us to. Knowing how to win arguments is the skill the sophist teaches, and it is the skill most at home in the law-court. Philosophical investigation also requires skill, and we have attended to some places where logical skill is not as developed as it should be. But philosophy requires more than skill, Plato suggests. It requires the virtue of loving the truth, which in turn implies a respect for rigor well expressed by Socrates dictum that whatever direction the argument blows us, that is where we must go (3.394d). In addition to respect for rigor, another sub-virtue is open-mindedness, which we might think of as openness to rational persuasion. We noted earlier how the Republics opening exchange raises the opposition between force and persuasion. When Polemarchus jokingly asks, But could you persuade us, if we will not listen? (1.327c), he is making the serious point that philosophical inquiry requires that we do not have a pre-determined outcome, as a lawyer trying a case might, or at least that we are open to countervailing reasons and evidence. The Philosophers Virtues 179 Intellectual Virtues and Character Virtues An interesting feature of this leading philosophical virtue is that loving the truth seems to straddle two distinct kinds of virtues, intellectual virtue and character virtue. Perhaps because he was by nature less taxonomically inclined than his student Aristotle (whose inclinations in this regard were no doubt shaped by his biological investigations), Plato does not explicitly distinguish between these kinds of virtue, as Aristotle does in his seminal work in moral philosophy, the Nicomachean Ethics. Readers will recall that a virtue is the state or condition that enables its possessor to perform its function well, where its function is its purpose or characteristic activity. A knifes function is to cut, so sharpness is its virtue, since a knife must be sharp if it is to cut well. Where character virtues such as moderation and courage enable morally correct behavior, intellectual virtues such as wisdom are traits that enable their possessors to gain knowledge. The function or goal they enable is knowledge. So genuine philosophers, Socrates tells us, must possess intellectual virtues such as quickness or ease in learning (6.486c, 6.487a, 6.490c, 6.494b, 6.503c) and a good memory (6.490c, 6.494b, 6.503c). The absence of the latter trait allows Plato a few jokes along the way: Glaucon, in admitting that he has forgotten that they aim to make the city as a whole happy and just (7.519e), thereby implicitly concedes that he lacks a philosophical nature, at least to some degree. Even Socrates himself admits that he cannot remember whose question prompted his articulating this principle (5.465e). And clearly a good memory will be important to the agreement-based, question-and-answer method they have adopted to investigate the Republics two main questions. Loving truth enables knowledge, since loving wealth or honor more than or instead of truth will hamper rather than enable learning. Thus love of truth seems, like being a quick learner or having a good memory, to be an intellectual virtue. But love of truth tells us not just about a persons intellect but also about their character, since it tells us about what they value. Thus it seems as much a virtue of character as an intellectual virtue. The person who loves the truth can be counted on to act well and rightly when for example truth and self-interest conflict. Moreover, some intellectual virtues such as quickness and 180 Platos Republic: An Introduction ease in learning are like skills in so far as they are morally neutral, depending for their moral status on the subjects learned and the end to which the knowledge gained is put. A quick learner with a good memory will master the mechanics of terrorism more quickly than a forgetful, slow learner will. Love of truth, by contrast, seems to lack this moral neutrality, as does wisdomat least on Platos conception of moral knowledge. If one really knows what is good, Plato has Socrates argue in the Protagoras, one would act on that knowledge if one were able to. The idea of knowing what is good or right but not acting on that knowledgethe problem of weakness of willis not a genuine possibility. Exploring whether Plato was right about this will take us too far afield, and unsurprisingly there is much scholarly debate on the topic. But this melding of moral knowledge and moral conduct helps us see why love of truth has a foot on each side of the divide between intellectual and character virtues. Another philosophic virtue worthy of our attention is highmindedness ( [megaloprepeia], which is sometimes translated as magnificence). Like many of the virtues discussed in Book VI, we first met high-mindedness in Book III (e.g., 3.402c), where it was implicit in the musical-poetic cultivation of courage: a decent man does not think that death is a terrible thing for someone to suffer (3.387d) and thus must be told stories that will make them least afraid of death (3.386a). High-mindedness is a virtue of knowing what really matters, what is worth taking seriously. Socrates suggests that a high-minded person will not consider human life to be something important (6.486a), but this is best taken as a point about lifes relative importance. It is not valueless, something to be thrown away on a whim, but it is not as important as the good of the city. Living is not itself an intrinsic good, though living well is. And if living well, which for Plato requires living justly, requires sacrificing ones life for the good of ones city, then the high-minded person will (ideally) have no hesitation in doing so. High-mindedness looms in the background of Platos deepest criticisms of poetry in Book X. Human affairs are not worth taking very seriously, Socrates insists in Book X (10.604b), and poetry is dangerously corrupting because it leads us to take [our] sufferings seriously (10.605d). Readers familiar with Stoicism will see its Socratic roots in the virtue of high-mindedness. The Philosophers Virtues 181 Virtues of Personal Style In addition to virtues of character and intellect, Socrates proposes another family of virtues as distinctive of the philosophical nature. Gracefulness, which we met back in Book III when discussing poetic meter or rhythm (e.g., 3.400c, 3.400d, 3.401a, 3.401d), is not a matter of character or intellect so much as a matter of personal, aesthetic style. Would-be philosopher-kings must be graceful ( [eucharis]) (5.487a), and indeed they approach the divine as they absorb gracefulness from studying the Forms (6.500c). We meet a similar group of personal-aesthetic virtues in Aristotles Nicomachean Ethics, where traits such as wit and sociability are on Aristotles official list of virtues, on a par with canonical, cardinal virtues such as courage and moderation. The way Plato and Aristotle treat such traits suggests that they did not draw a sharp line between character and personality, between moral and non-moral traits, as we moderns tend to do. Their attitudes toward the personal-aesthetic virtues suggests a more holistic, integrated picture of human goodness on which calling someone a good person is not an exclusively moral evaluation. There is a lively scholarly debate about whether our modern notion of morality is even to be found in ancient Greek philosophical thought. At the very least, it seems safe to say that beauty and goodness are more intimately connected for Plato and Aristotle than they are for us. Proper aesthetic sensibility is the basis for morality; and the crucial notion of what is kalonfine or noble or beautifulis inescapably aesthetic. A Game of Checkers (6.487bd) It is perhaps surprising that a willingness to speak up and challenge assertions that others accept does not make Socrates list of philosophical virtues. It is certainly an admirable trait, and one that Adeimantus displays with some frequency throughout the Republic. In Book II, after Glaucon raises the issues he want Socrates to address, Adeimantus insists that the most important thing (which he takes to be the hypocritical way Athenian culture praises justice) has not been said yet (2.362d). Book IV begins with Adeimantus questioning how ideal the ideal polis can be, given that the guardian-rulers austere 182 Platos Republic: An Introduction lifestyle will leave them unhappy (4.419a). And Book V begins with Adeimantus (prompted by Polemarchus) interrupting Socrates immediately moving to consider the Republics second question, when he still has questions about the way Socrates has answered the first, which prompts the Three Waves. Adeimantus shows that interrupting a speaker is not always rude, and he models a willingness to not be cowed by an intellectual superior. Here in Book VI Adeimantus jumps in to answer a question Socrates has posed to Glauconnot the first such interruption in the Republicabout whether he would be willing to entrust the city to the philosopher-kings whose nature he has been describing (6.487a). Adeimantus does not object to particular claims Socrates has made; he does not deny that philosophers must be courageous or quick learners, nor does he challenge the status of the personal-aesthetic virtues. Instead, he offers a broader objection, suggesting that Socrates whole procedure is unlikely to persuade anyone to entrust the city to [philosophers] and to them alone (6.487a). He articulates the perspective of people who are not convinced by the Socratic chain or reasoning, feeling merely outmaneuvered and not persuaded: Just as inexperienced checkers players are trapped by the experts in the end and cannot make a move, so too they [i.e., your vanquished interlocutors] are trapped in the end and have nothing to say in this different kind of checkers, which is played not with disks but with words. Yet the truth is not affected by this outcome. I say this with a view to the present case, for someone might well say that he is unable to oppose you as you ask each of your questions, yet he sees that of all those who take up philosophy [] the greatest number become cranks, not to say completely vicious, while those who seem completely decent are rendered useless to the city because of the studies you recommend. (6.487bd) Polemarchus, for one, knows whereof Adeimantus speaks: Socrates argued in Book I that defining justice as benefiting friends and harming enemies led to the conclusion that the just person is a kind of thief and justice itself is a craft of stealing. When asked if this is what he meant, Polemarchus insists, No, by god, it is not. I do not know any more what I did mean, but I still believe that to benefit ones friends and harm ones enemies is justice (1.334b). There were good reasons for him to resist the conclusion Socrates has led him to, but even though he did not see The Philosophers Virtues 183 what these reasons were and thus how he could resist the conclusion, Polemarchus hung on to his definition of justice, feeling outmaneuvered by Socrates rather than persuaded by him. Adeimantus is not accusing Socrates of acting in bad faith but rather is pointing out that Socrates is perceived by many of his fellow citizens not as better at arriving at moral truth but simply better at intellectual checkers than they are. They can and will persist in believing their seemingly refuted views, since Socrates philosophical argumentation seems to be nothing more than a kind of game of contradiction (7.539b). In short, to Socrates question about entrusting the city to philosopherkings, the solution to the Third WaveAdeimantus seems to be saying, Well, I might entrust the city to them, Socrates, but most people will not. Why would they, when they think of philosophers as useless at best and vicious at worse? They will nod in seeming agreement with you, but nothing you have said so far will change their minds: they think you are just playing word-games. It is no accident that it is Adeimantus who in Book II insiststwice (2.367be)that Socrates not merely give yet another theoretical argument that the just life is happier. Here he is doing much the same thing, asking not for a reworked version of the Powers Argument but for something less abstract and more accessible. Socrates obliged Adeimantus request in Book II by offering the city-soul analogy, which of course structures the rest of the Republic, and here in Book VI he responds in a similar but even more procedurally transparent vein: The question you ask needs to be answered by means of an image or simile (6.487e). So Socrates will meet Adeimantus checkers metaphor with one of his own, meant to show why his fellow citizens regard philosophers as useless. Analogical thinking is at the heart of the Republic. Its very method is analogical, asking us to think about the nature and value of justice as a virtue of persons by first thinking about it as a virtue of city-states. Here in Book VI, Socrates explicitly appeals to similes (6.487e, 6.488a, 6.489a) and analogies (the Greek terms are [eikn: likeness, image, reflection], from which we get the English word icon, and [analogon: proportionate to, resembling], from which we get the English word analogy). Socrates, who describes himself as greedy for images (6.488a), is forgoing the longer and fuller road that leads to precise 184 Platos Republic: An Introduction answer[s] (4.435c) in favor of a less demanding path that offers a view of the same truths the more demanding path leads to, but the view is less clear and distinct. The road of dialectic, which requires doing without hypotheses and metaphors (6.511ae, 7.533c), is not just longer; it is a rough, steep path (7.515e) that only those few who are blessed with a philosophical nature are capable of following. The rest of usmost of us, given that the majority cannot be philosophic (6.494a)will have to be content with an easier, less rigorous path. In the next chapter we will explore the major metaphors of Books VI and VIIthe analogies of the Sun, Line, and Cave. Here we will look briefly at Socrates analogical response to Adeimantus challenge. Given the critique of painting, poetry, and the other imitative arts that awaits us in Book X, it is striking that here Socrates embraces the role of painter ( [graphs] (6.488a)) as he constructs his analogies. The Ship of State Sails the Third Wave (6.487e490e) Socrates surprising response to Adeimantus suggestion that most people think that philosophers are useless at best and vicious at worst is that they seem to me to speak the truth (6.487d). The seem will turn out to be important: Socrates does not think genuine philosophers really are useless or vicious, but he understands that people who do not distinguish the genuine philosophers from the pretenders will think they are. It is in this spirit that he offers the Ship of State analogy, hoping to explain what the most decent people experience in relation to their city (6.488a) and why they think philosophers are useless. Think of the city as a ship, he suggests. Whom should the owner select as its captain? Obviously, the owner should select the person who possesses the art of navigation (6.488b), since only a person possessing the relevant nautical skills has sufficient knowledge to chart the appropriate course to get the ship safely to its destination. But the owner, who knows nothing of navigation and is near-sighted and hard of hearing, to boot, will not choose the true captain (6.488e), alas. The sailors clamor for the job, but while each of them understands his particular role on the ship and can follow the captains orders, none of them is qualified to give such orders, despite thinking they are. (This is an early instance of the Dunning-Kruger Effect, a cognitive bias leading The Philosophers Virtues 185 people to overestimate their abilities and fail to recognize their lack of competence in certain areas.) The owner chooses not the person skilled in navigation but rather the person who is clever at persuading or forcing the shipowner (6.488d), with predictably bad results. And analogously the citizens choose for their ruler not the person who possesses wisdom and knows what is best for the city as a whole, but rather someone who charms and flatters them. But why blame the philosophers and regard them as useless?, Socrates seems to ask. That they are not in fact chosen for the job for which they are qualified tells us more about their fellow citizens than it does about them. Just as genuine captains do not beg ship owners for jobs or doctors do not beg the sick to be allowed to treat them, it is not for the ruler, if he is truly any use, to beg the others to accept his rule (6.489c). Rulers, doctors, and captains are entitled to maintain their selfrespect, which presumably entitles them to refuse to sing along to the Temptations Aint Too Proud to Beg as they go about their business. But given that what is at stake is the wellbeing of the city, perhaps this seemingly legitimate pride is a vice, not a virtue. We will see in Book VII that Socrates thinks that possessing political wisdom does not in itself entail an obligation to seek to govern; only a philosopher-king or -queen raised by the ideal city would be under such an obligation. One might think that those who possess political wisdom should be sufficiently interested in the wellbeing of their city for a bit of begging to be in order. This might seem to go against Platos dictum that it is those who are not lovers of ruling who must rule (7.521b), but one can be willing to rule without loving ruling, if only to avoid the punishment of being ruled by someone worse than oneself (1.347c). The historian Gordon Wood remarks that at least early in American political life, Gentlemen generally stood, not ran, for election, and canvassing for an office, as [Aaron] Burr was said to have done for the vice-presidency in 1792, was widely thought to be improper.1 Perhaps Socrates shares something like this view and thus regards actively seeking office as unseemly. 1 Gordon S. Wood, Empire of Liberty: A History of the Early Republic, 17891815 (New York: Oxford University Press, 2011), p. 160. 186 Platos Republic: An Introduction Tending the Beast (6.490e495a) Against those genuine, wisdom-possessing philosophers are people who seem to possess wisdom but actually do not: sophists. If we think of the citizens of Athens as a huge, strong beast (6.493a), these sophists have a knack for learning how best to placate the beast, how to take advantage of its moods and satisfy its appetites. But the pseudo-philosophical sophist knows nothing about which of [the beasts] convictions is fine or shameful, good or bad, just or unjust, but he applies all these names in accordance with how the beast reactscalling what it enjoys good, and what angers it bad. He has no other account to give of these terms (6.493b). The sophists wisdom consists in telling the beast what it wants to hear, which echoes a point Socrates made earlier: The person who is honored and considered clever and wise in importance matters by such badly governed cities is the one who serves them most pleasantly, indulges them, flatters them, anticipates their wishes, and is clever at fulfilling them (4.426c). Sophists, mere pretenders to wisdom, are adept at tending the beast (6.493b), but their skill lies in persuasion, not truth-seeking. (In the dialogue the Gorgias, Plato has Socrates suggest that the sophists fall short of possessing skill or craft ( [techn]) and instead merely have a knack ( [empeiria], whence the word empirical) but we can safely ignore that interesting issue here.) What they possess is not wisdom, but it is not really surprising that it passes for wisdom. After all, most of us are prey to flattery, and for Socrates and Plato, the majority cannot be philosophic (6.494a)hence the anti-democratic nature of the ideal polis. For Plato, it is not merely the case that most of us do not possess wisdom, but rather that most of us cannot possess it. Given his conception of knowledge, we can see why he holds this strongly anti-democratic view. Wisdom is knowledge of what is best for the city as a whole, and to possess such knowledge one must grasp the Form of the good. Only someone with this stable, true model of goodness will be able to establish here on earth conventions of what is fine or just or good (6.484d). Readers who do not share Socrates austere conception of knowledge will likely think that genuine wisdom, while still rare and very different from the focus-group politicking of modern sophists, is more common than Socrates allows. The Philosophers Virtues 187 Shelter from the Storm (6.496a497c) Suppose that Socrates is right that no one can be happy in a polis not governed by philosophers. Given the madness of the majority and the fact that hardly anyone acts sanely in public affairs (6.496c), a person trying to live wellwhich requires living justlyis like a man who has fallen among wild animals and is neither willing to join them in doing injustice nor sufficiently strong to oppose the general savagery alone (6.496d). What should such a person do? I suspect that many readers will be disappointed by Socrates answer. For rather than urging political engagement to reform and improve a polis that falls short of their ideals of justice or advocating revolution to overthrow a polis that is not merely non-just but is positively unjust, Socrates instead counsels withdrawal from public affairs, urging those who want to live justly in unjust city-states to lead a quiet life and do their own work [] like someone who takes refuge under a little wall from a storm [] [and] is satisfied if he can somehow lead his present life free from injustice and impious acts and depart from it with good hope, blameless and content (6.496d). Many politically inclined readers will reject this approach, seeing it as acquiescent to injustice, but the fair-minded among them should be able to appreciate why some will find it attractive. While Socrates preferred path seems apolitical, its defenders might reply that he is actually offering a different kind of politics, one that is interior rather than exterior: keep the constitution of the ideal city firmly in mind and make oneself its citizen (9.592b). As with the virtue of highmindedness discussed earlier, we can see here the seeds of the stoic idea of cosmopolitanism: one is not primarily a citizen of the city-state one inhabits in space and time but rather a universal polis. And surely high-mindedness is at work as one seeks shelter from the storm: if indeed Human affairs are not worth taking very seriously (10.604b), why not tend to ones inner polis rather than muck about in the outer one, especially since that outer polis will be genuinely habitable only by a remarkable stroke of luck or by divine intervention: no city, constitution, or individual man will ever become perfect until either some chance event compels those few philosophers who are not vicious (the ones who are now called useless) to take charge of a city, 188 Platos Republic: An Introduction whether they want to or not, and compels the city to obey them, or until a god inspires the present rulers and kings or their offspring with a true erotic love for true philosophy. (6.499b) Many readers will share Socrates pessimism about the likelihood that theor anideal polis can be realized in the actual world, but many will be troubled at his seeming to reject political action as well as what seems to be his focus on the ideal world rather than the admittedly imperfect actual world. Looking at how Socrates himself lived in Athens, a polis that fell far short of the ideal that Plato sketches in the Republic, might be instructive here. Did Socrates follow his own advice? He did not pack up and leave, even after being convicted of impiety and corrupting the youth in a trial that, however procedurally fair it was, yielded what seems a substantively unjust verdict. He refuses to leave, because the best arguments lead him to conclude that leaving would be unjust. Socrates did not lead a quiet life; if he had, it is unlikely that we would ever have heard of him or that Athens would have treated him as it did. But he did his own work, as he conceived of it. His Godgiven work, he tells us in the Apology, was to be a gadfly, questioning and exhorting Athenians to virtue (30e). In his final words to the jurors, he asks them to do for his sons what he tried to do for them: to correct them if they seem to care about riches, or anything, more than about virtue (41e). So it seems that Socrates did not live the quiet life he counsels. But when the so-called Thirty Tyrants, installed by Sparta to govern Athens after the end of the Peloponnesian War, demanded that Socrates bring them Leon of Salamis for execution, he refused, regarding the act as unjust and impious. So his eschewing politics did not entail complicity in injustice or collaboration with the unjust. Alas, though, he did not try to prevent others from doing so, nor did he try to warn Leon. While the others went to Salamis to fetch Leon, Socrates went quietly home (32d). The Philosophers Virtues 189 Some Suggestions for Further Reading For an excellent discussion of virtue and the virtues, interested readers should see Heather Battaly, Virtue (Malden, MA: Polity Press, 2015). The philosophical literature on truth is vast. A good place to start is Michael P. Lynch, True to Life: Why Truth Matters (Cambridge, MA: MIT Press, 2004), https://doi.org/10.7551/mitpress/6919.001.0001 Readers interested in the question of morality and the ancient Greeks will benefit from Richard Kraut, Doing without Morality, Oxford Studies in Ancient Philosophy, 30 (2006), 159200, although his focus is explicitly on Aristotle. Bernard Williams famously claims that Greek ethical thought [] basically lacks the concept of morality altogether, in the chapter Philosophy, in The Legacy of Greece: A New Appraisal, ed. by M.I. Finley (Oxford: Clarendon Press, 1981), pp. 20255. Readers interested in the personal-aesthetic virtues will find much of interest in Aristotles Nicomachean Ethics, excellently translated by Terence Irwin (2nd ed., Indianapolis: Hackett Publishing, 1999), especially Book IV, which discusses virtues such as friendliness, wit, and magnificence. Readers interested in the trial and death of Socrates will want to read at least the Apology and Crito, available (among other places) in Five Dialogues: Euthyphro, Apology, Crito, Meno, Phaedo, trans. by G. M. A. Grube, ed. by John Cooper (Indianapolis: Hackett Publishing, 2002), which contains other dialogues of great interest. Thomas Brickhouse and Nicholas Smith, Socrates on Trial (Princeton: Princeton University Press, 1990) is an excellent discussion, and I.F. Stone, The Trial of Socrates (New York: Anchor Books, 1989) offers an interesting and very unsympathetic take on Socrates. Xenophon, Conversations of Socrates, trans. by Robin Waterfield (New York: Penguin Books, 1990), presents an interestingly different picture of Socrates than Plato does, though both are Socrates contemporaries. Achilles and Ajax playing a board game overseen by Athena (c. 510 BCE). Photograph by Aisha Abdel (2018), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/Category:Black-figure_pottery#/ media/File:Attic_Black-Figure_Neck_Amphora_-_Achilles_and_Ajax_ playing_a_board_game_overseen_by_Athena.jpg 10. Metaphors to Think by: The Sun and Divided Line Analogies, Book VI The analogies we looked at in the last chapter are interesting, but they are merely appetizers to the metaphorical feast Socrates soon serves, which features the Sun, Line, and Cave analogies (the last of which we will cover in the next chapter). It is philosophical fare of the highest order, since the topic is the most important subject which is even more important than justice and the other virtues (6.504d)the Form of goodness itself: the form of the good is the most important thing to learn about [ since] it is by their relation to it that just things and the others become useful and beneficial [] [but] we have no adequate knowledge of it (6.505a). The Greek rendered by the form of the good is (h tou agatou idea)literally, the idea of the good. As noted earlier, for Plato an is not an idea in our ordinary sense but rather something that is not only mind-independently real but is actually more real than the many particular instances of it. The metaphysical elevator goes all the way up to Level Four, though here Plato implies that there is yet another floor, where a very special Form, the Form of the good, resides. To get a sense of the importance of the Form of the good, consider first the distinctive virtue of the philosopher-rulers, political wisdom. Political wisdom is knowledge of what is best for the city, but one cannot know what is superlatively good for the city without understanding what goodness itself is: I do not suppose that just and fine things will Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.10 192 Platos Republic: An Introduction have acquired much of a guardian in someone who does not even know in what way they are good. And I divine that no one will have adequate knowledge of them until he knows this (6.506a). Although one can believe that something is good without grasping why it is, one cannot know that something is good without knowing why that thing is goodand one cannot know this, Socrates thinks, without knowing what goodness itself is. A ruler who does not understand what goodness itself is will at best have true beliefs about what is good for the city, but that falls far short of the knowledge required for genuine wisdom. So what is the Form of the good, goodness itself? What the Good Is Not (6.505a-d) Socrates does not claim to know what the good is, but he does think he knows what it is not. Narrowing the field by excluding unworkable options is a kind of intellectual progress, and so he begins with two untenable accounts of the nature of the good. The first view, held by the majority is the view that pleasure is the good (6.505b). This is hedonism, the view that pleasure is the only thing that is good in itself. Any other thing that is good is good extrinsically, by being a means to the one intrinsically good thing, pleasure. Although they often run in the same harness, hedonism is distinct from egoism, the view that ones interests count for more than the interests of others (perhaps because others interests do not count at all). Classical utilitarians such as Jeremy Bentham and John Stuart Mill were hedonists but not egoists. They regarded total net pleasure, the result of subtracting the pain an action produces from the pleasure it produces, as the standard of right action, where the interests of all parties affected by the action are given equal weight. Socrates immediately locates a problem for hedonism: there are bad pleasures (6.505c), which even hedonisms advocates will concede. Although he does not give any examples, they are not hard to come by. Imagine a peeping Tom who is very careful not to be seen; he derives a great deal of pleasure from spying on his neighbors through his highpowered (and well-hidden) telescope, and they are none wiser, so there is no pain he is inflicting to offset the pleasure he produces for himself. Metaphors to Think by 193 But his action still seems wrong, and his pleasure is an evil pleasure, as almost anyone would think. Even though philosophical questions are not best settled by majority vote, anyone who concedes that the peeping Toms pleasure is bad should reject hedonism, for how can pleasure be what is good in itself if there are pleasures that are bad in themselves? The second view Socrates considers has a bit more going for it than hedonism; if nothing else, it is held by more sophisticated folks. It is the view that the good [] is knowledge (6.505b), which we might awkwardly dub Epistemicism (from the Greek word for knowledge, epistem). This seems like a view that Socrates would find attractive, given the centrality of knowledge to philosophy, but he quickly dismisses itnot, as with hedonism, because there are instances of bad knowledge (though presumably there are) but because Epistemicism leads to an infinite regress (or, more properly, an infinite progress). Knowledge always has an object, he reminds Glaucon. If I have knowledge, I have knowledge of or about something; there is no such thing as mere, objectless knowledge. The various crafts are similar in being knowledge of how to do certain things, but they are distinguished by their objects: farmers know how to farm, doctors know how to heal, etc. Similarly, the grammarian and mathematician both possess the same kind of knowledgetheoretical or propositional knowledge that certain propositions are true, as opposed to knowledge of how to do thingsbut they too are distinguished by their objects. If we ask the sophisticates who hold that the good is knowledge what that knowledges object is, they will reply, Socrates thinks, that it is knowledge of the good (6.505b). This is highly problematic, and not just because it is circular. If the good is identical to knowledge, then for every occurrence of the good we can substitute knowledge, just as we can substitute 2+1 for any instance of 3 in a mathematical formula (e.g., since 32 = 9, it follows that (2+1)2 = 9). But if the knowledge in question is knowledge of the good, then the Epistemicists core claim, (E) The good = knowledge. becomes (E*) The good = knowledge of the good. But by substituting knowledge of the good for the good, (E*) generates 194 (E**) Platos Republic: An Introduction The good = knowledge of the good knowledge of the good, which in turn generates (E***) T he good = knowledge of knowledge of knowledge of the good, and so on, with no end in sight! Clearly, Socrates thinks knowledge is good. But it is a good, not the good. It is one of philosophys distinctive goods, but knowledge is not the goodit is not what goodness is. But even if we do not know what the good is, Socrates thinks we know two things it is not, and that is at least a start. So what does Socrates think the good is? The Analogy of the Sun (6.506d509d) Socrates does not answer this question directly, but not because he is being cagey, as Thrasymachus might suggest. And not (at least not explicitly) because he thinks the good cannot be defined in any non-circular way. The eighteenth-century philosopher Joseph Butler remarked that Everything is what it is, and not another thing, which the twentieth-century philosopher G.E. Moore quoted at the outset of his Principia Ethica before arguing that any attempt to give a real definition of goodness was doomed to fail. Cinema lovers may recall a memorable exchange in the film The Deer Hunter between Mike (Robert De Niro) and Stanley (John Cazale), in which Mike, holding up a bullet, says, Stanley, see this? This is this. This aint something else. This is this.1 Stanley does not understand the lesson, but I suspect Socrates, Butler, and Moore would all be sympathetic to Mikes point, since the good is what it is and not some other thing. So why does Socrates not provide a value for x in the philosophical equation the good = x? Why does he choose to abandon the quest for what the good itself is for the time being (6.506d)? Although antagonists like Thrasymachus will scoff, I believe it is because Socrates possesses the virtue of epistemic humility: he claims not to know what the good is and insists that one should not talk about things one does not know as if one does know them (6.506c), which is what hed be 1 The Deer Hunter, dir. by Michael Cimino (Universal Pictures, 1978). Metaphors to Think by 195 doing if he responded directly to Adeimantus request for an account of the good. But while he cannot say what the good is, he thinks he can say something about what it is like, which brings us to the Sun Analogy. In Book VII Socrates will suggest that dialecticrigorous, Forms-based philosophical reflectionis the only avenue to genuine knowledge. As he did earlier in Book VI, he reminds Glaucon and company that they will be avoiding this longer road (6.504c) and proceeding in a less exact, hypothetical way which will give them a sense of what the good is, but which will fall well short of full-blown philosophical knowledge of it. Socrates plan is to explain the Form of the good in terms of something more readily understandable: the sun. He suggests that the goodthe Form or essence of goodness itselfplays the same role in the intelligible realm that the sun plays in the visible realm. Strictly speaking, the focus is the suns role in the sensible realm, the world of sense-experience, but we will follow Socrates in using visible to designate this realm, which also includes what he can hear, touch, taste, and smell as well as what we can see. While he cannot say what the good is, he can say what he thinks the good does. His idea is that the sun: the visible world :: the good: the intelligible worldthe roles the sun and the good play in their respective worlds are analogous. In the visible world, the sun by its light enables us to see the many particular thingsand also enables their existence. In the intelligible world, the good by its truth enables us to know the Formsand also enables the existence of the Forms. Seeing something requires both a visible object and the power of sight. But it also requires a third kind of thing (6.507d)light. Without light to illuminate the object, the power of sight will not reveal that object to us. The sun is the main and most obvious source of light, so the sun enables us see visible objects. But it does more than enable their being seen, Socrates thinks; it enables their very existence. This is certainly true of living things, which depend for their existence on the light of the sun. (It is less clear that this is true of rocks, but we need not be sticklers about this.) The same goes for the Form of the good: what gives truth to the things known and the power to know to the knower is the form of the good. And though it is the cause of knowledge and truth, it is also an object of knowledge [] not only do the objects 196 Platos Republic: An Introduction of knowledge owe their being known to the good, but their being is also due to it. (6.508e9b) So, just as the sun provides the light that enables us to see visible objects, the Form of the good provides the truth that enables us to know intelligible objects, which of course are the forms: the many beautiful things and the rest are visible but not intelligible, while the [F]orms are intelligible but not visible (6.507b). Beautiful things owe not only their being seen but also their very existence to the sun. Similarly, the Form of beauty depends for both its knowability and its very existence on the Form of the good. Thus the Form of the good plays a foundational role in Platos epistemology, since it is the condition of all knowledge, and also in his metaphysics, since it is the condition of the existence of the other Forms and in turn the existence of concrete particular objects. Particular beautiful things are beautiful because they partake, if only temporarily, in the Form of beauty; they are temporary, spatiotemporal images or copies of the Form of beauty itself. Similarly, a particular just action or soul is just because it participates in the Form of justice, and so on. And since beautiful things and just actions are good and useful, they must also participate in the Form of the good: it is by their relation to [the Form of the good] that just things and the others become useful and beneficial (6.505a). Thus the Form of the good subsumes the Forms of justice, wisdom, courage, etc.; not only would they not be good without it, they would not exist without it. So goodness is at the core of Platos conception of the universe, both epistemologically and metaphysically. The Divided Line (6.509e511e) Socrates follows the Sun Analogy with a linear perspective on how the visible and intelligible worlds differ. His focus here is largely epistemological, though as we might expect metaphysics looms in the background. Having already said a bit about how knowledge and belief differ, here Plato goes into more detail, saying more about their distinct objects (thus drawing on the ill-fated Powers Argument) and also making distinctions between different kinds of knowledge and belief. We can think of the line as a sort of epistemological companion to the Metaphysical Elevator, in which one ascends epistemologically from Metaphors to Think by 197 belief to knowledge and metaphysically from concrete particular objects to the Form of the good. Start a line segment and divide it unevenly, as below, into two subsegments. Let one segment represent the visible world and the other the intelligible world: Fig. 1. The Visible World and the Intelligible World Belief is the epistemic state (or, as Socrates would have it, the power) that operates in the visible world, while knowledge governs the intelligible world. Since length corresponds to relative clarity and opacity (6.509d), the line segment representing the intelligible realm will be longer than the segment representing the visible realm. This should make sense, given Platos view that the Forms, which are at home in the intelligible realm, are both more real than the particulars and are epistemically clearer: the Forms are objects of knowledge, while the particulars are objects of belief. Belief, while clearer than ignorance, is darker and opaquer than 198 Platos Republic: An Introduction knowledge, as Socrates claimed earlier (5.478c). So, even though there are more objects in the visible world than in the intelligible world, since the relation between particulars and their Forms is a relation of many to one, the segment representing the intelligible realm is longer than the segment representing the visible realm. Now here comes a slightly tricky part: divide each sub-segment again by the same ratio as the entire line was divided: Fig. 2. The Visible World (a and b) and the Intelligible World (c and d) So now the visible world comprises sub-segments a and b and the intelligible world comprises c and d, and with the ratios of both a to b and c to d identical to the original ratio of Visible to Intelligible. An obvious consequence of this is that a:b :: c:d. A less obvious consequence, which Socrates either does not notice or notices but does not mention, is that b and c turn out to be the same length. Given that the line is arranged in terms of relative clarity and opacity (6.509d), the equality of b and c suggests an epistemic and metaphysical parity between the Metaphors to Think by 199 highest visible and lowest intelligible sub-sections of the line, and it is hard to see Socrates endorsing such a view. This is at least a wrinkle in the Divided Line analogy, but let us assume that it is a wrinkle that can be ironed out and move on. Now we will see the parallel between metaphysics and epistemology. Plato further divides the main epistemic states or powers, Belief and Knowledge, which appear on the lines right side in Fig. 3: Fig. 3. The Visible World and the Intelligible World: Belief and Knowledge The two bottom sub-segments of the line, a and b, which together make up the visible realm, have different objects. The lowest level, a, has images ( [eikones]) for its objectsshadows and reflections and, presumably, the analogies and metaphors of the sort that Socrates is so greedy for in Book VI, as well as the paintings, sculptures, and poems 200 Platos Republic: An Introduction that he will criticize in Book X. The second lowest level, b, comprises the original items of which those images are copies. The bed in which Van Gogh slept in his room at Arles, which served as the model for his famous paintings of it, would be an object appropriate to b, while the paintings of the bed, being copies of that spatiotemporal object, belong in a. In addition, we might think the second-hand opinions that many of us have, opinions we merely parrot from our favorite news source, belong here in a. Many readers active on Facebook or Twitter will be familiar with someone whose social media mission seems to be reposting or re-tweeting stories and memes that express the views they have gotten from others. (When someone says, I have thought about this a lot, one hopes they mean this literally, where thought is a verb, and they have scrutinized and analyzed and seen implications of the point in question. What we are often saying, alas, is I have a thought about this, and I think that thought a lot, where thought is a noun, and thinking that thought does not require critical examination of the ideas merits and demerits, etc.) In addition to their different objects, a and b also differ in terms of the epistemic or cognitive states operating in them. While Plato generally talks of belief ( [doxa]) as operating in the visible realm, here he distinguishes between [eikasia], imagining (or merely imaging) and [pistis], which is translatable as belief but which suggests credence, trust, and sincerity as well. The intelligible realm is where the Forms live. While the sub-segments of Visible had different kinds of objects, here the objects are the same: Forms (although the Form of the good operates in d, the highest level). Segments c and dThought ( [dianoia]) and Understanding ( [nosis]), respectivelyare distinguished by how knowers are related to the Forms that populate the intelligible world. Hypotheses and First Principles in the Divided Line A crucial difference between Thought (c) and Understanding (d) is the role that hypothesis ( [hypothesis], literally, what is placed or set under something) plays. Mathematicians, who occupy themselves in Thought, employ hypotheses in their thinking: they hypothesize the odd and the even, the various figures, the three kinds of angles (6.510c), etc. But, Socrates thinks, they do not think it is necessary to give any Metaphors to Think by 201 account ( [logos]) of them (6.510c), presumably because these hypotheses seem so obviously true that no justification is needed. Just as mathematicians take it for granted that there are numbers and triangles, physicists assume the existence of an external world of spatiotemporal objects, whose properties and behavior they study without feeling the need to justify this assumption. They treat their hypotheses as first principles ( [arch])) (6.510d)as foundationsand draw conclusions from them. The mathematicians conclusions are not about the particular triangle or circle drawn on the blackboard; the physicists are not about the particular electrons in this particular cloud chamber; rather, they are about triangles and circles in themselves, or about electrons in themselves. Both try to prove things about the Forms, on the model of inquiry depicted by the Divided Line. By contrast, the philosopher, who roams the realm of Understanding, recognizes hypotheses as hypotheses; they do not think of their hypotheses and assumptions as self-evidently true first principles requiring no justification. Unlike their mathematical and scientific cousins, the philosopher does not treat a hypothesis as an unassailable foundation or first principle but rather as something that stands in need of a logos, a justification or rationale. The hardest part of philosophy, Socrates says, has to do with giving a rational account (6.498a). It is not that mathematicians and scientists are too lazy to justify their hypotheses, but rather that they do not feel the need to do so, since their assumptions seem so obviously true. But so long as the foundational hypothesis is unaccounted for, what follows cannot fully count as knowledge, on Socrates view, even though it involves grasping mathematical Forms: What mechanism could possibly turn any agreement into knowledge when it begins with something unknown and puts together the conclusion and steps in between from what is unknown? (7.533c) Socrates implies here that mathematicians can give valid arguments (arguments whose conclusions must be true if their premises are true), but that the conclusions of their arguments are merely conditionally and not absolutely true. That is a far cry from giving an argument whose conclusion must be true, period, which would require showing that the hypotheses in question are true and do not merely seem to be true. While the mathematicians valid arguments might be sound, the 202 Platos Republic: An Introduction mathematician is never in a position to know whether their arguments are sound or not until they justify the hypothesisthe ifon which the conclusion ultimately rests. To get a sense of what is at stake, consider a hypothesis that many readers encountered in high school geometry class, Euclids parallel postulate. That parallel lines extended indefinitely in space will never meet seems so intuitively obvious as to be axiomatic. No wonder geometers do not try to give an account of this hypothesis. Doing so seems a waste of time, and developing a geometry that rejects that postulate seems a fools errand. But, as many readers know, the geometry required for Einsteins general theory of relativity is nonEuclidean, geometry that rejects the parallel postulate. Space, on Einsteins view, is curved, so Euclidean geometry misdescribes it. The assumption that parallel lines indefinitely extended in space would never touch seemed too obvious to need a justification, but it turns out to be false. That is the kind of worry Socrates has about the realm of Thought. Dialectic and Understanding It is not that hypotheses are dispensed within the realm of Understanding. Instead, they are treated as hypotheses, as needing justification, rather than as first principles requiring no justification: It does not consider these hypotheses as first principles but truly as hypothesesstepping stones to take off from, enabling it to reach the unhypothetical first principle of everything. Having grasped this principle, it reverses itself, and, keeping hold of what follows from it, comes down to conclusion without making use of anything visible at all, but only of forms themselves, moving on from forms to forms, and ending in forms. (6.511b) Understanding is the result of what Socrates calls dialecticthat is what the initial it in the quotation just above refers to. Dialectic is the longer, harder road that Socrates chooses not to travel in the Republic, opting instead for a discussion relying on analogies and metaphors. Dialectic is like mathematical thinking in having the Forms for its objects, but, as we just noted, dialectic treats hypotheses and assumptions differently than mathematical thinking. Here are Metaphors to Think by 203 some of dialectics distinctive features, which ground ways in which Understanding differs from Thought: 1. Giving an account. The dialecticiani.e., the genuine philosopheris able to give an account of the being of each thing (7.534b). In addition to being able to grasp the essence of the thing under discussion, the philosopher is also able to explain that essence, to give an account of it. Someone who is able to give an account of the being of each thing [is] dialectical, Socrates says. But insofar as he is unable to give an account of something, either to himself or to another [] he has [no] understanding of it (7.534b). Book Vs lovers of sights and sounds may have many true beliefs about which objects are beautiful, but being unable to grasp the Form of beauty, they are unable to explain why a beautiful thing is beautiful, and thus lack knowledge. Similarly, the geometer who assumes that the parallel postulate is true but who is unable to justify that assumption lacks Understanding: they think with concepts they do not fully understand. 2. Integrated knowledge. Presumably, the mathematician is able to give an account of the various mathematical objects she concerns herself with. But the dialectician is also able to see connections between the individual Forms: she sees their association and relationship with one another (7.531c) and so achieves a unified intellectual vision. Anyone who can achieve a unified vision is dialectical, Socrates says, and anyone who cannot is not (7.537c). A geometer is probably able to achieve a unified grasp of the various geometric Forms; it is hard to imagine someone specializing in, say, rectangles who knows nothing about circles or spheres or trapezoids. But the philosopherthe dialecticianis able to unify different domains of study, understanding not just geometry and physics or game theory and biology in themselves, but grasping how these disciplines and the Forms they study are interrelated. In short, the philosopher sees and makes connections between disparate domains. 3. Purely formal reasoning. Thought relies on visual aids: the geometers object in trying to prove a theorem about the nature of triangles is the Form of triangularity, but they draw particular triangles on particular chalkboards as an aid for grasping the triangles essence. Those drawings are aids borrowed from the visible realm. Understanding, by contrast, proceeds without making use of anything visible at all, but 204 Platos Republic: An Introduction only of Forms themselves, moving on from forms to forms, and ending in forms (6.511b). The dialectician is able to think with the Forms alone: her seeing is purely intellectual, and does not involve any objects from the visible realm at all, or the kinds of metaphors Socrates employs to make sense of the Form of the good. Dialectic tries through argument and apart from all sense perceptions to find the being of things and does not give up until he grasps the good itself with understanding itself (7.532a). 4. The Form of the good. Perhaps dialectics most distinctive feature, and thus the most important difference between Understanding and Thought, is that dialectic involves seeing how the various Forms are related to the Form of the good. Thus dialectic requires the most complete kind of intellectual integration possible. This integration is both horizontal, so to speak, understanding how Forms are related to each other, and also vertical, understanding how these Forms are related the Form of the good, which, as the condition of both the knowability and existence of the Forms, is at a level higher than themLevel Five, so to speak, on Platos Metaphysical Elevator. Platos universe is fundamentally ordained toward the good: the Form of the good is the unhypothetical first principle of everything (6.511b), and one does not fully grasp a things essence until one grasps the end it aims at, as well. Dialectical understanding is thus a very tall order. 5. Foundationalism. The contemporary epistemological distinction between foundationalism and coherentism sheds light on the difference between Thought and Understanding. Even though Plato does not think of knowledge as justified true belief, his concern with giving an account implies that a discussion of justification is not completely out of order. A coherentist holds that a beliefs being justified is a matter of its being properly related to other beliefs: ones beliefs hang together in a coherent way, with minimal inconsistency between beliefs. Presumably some inconsistency has to be allowed; otherwise no ones beliefs would be justified, since we all unknowingly have beliefs that are at odds with each other. The foundationalist, by contrast, thinks that at least one belief must be justified in a non-inferential way, not getting its justification from another belief. Such a belief is the foundationthe archof the justification of all other beliefs. Metaphors to Think by 205 The realm of Thought is coherentist: the mathematicians conclusions are in full agreement with the hypotheses they treat as first principles. The realm of Understanding, by contrast, is foundationalist: it rests ultimately on the Form of the good, which is the source of the intelligibility (and indeed the existence) of the other Forms. Ironically, the procedure for determining whether one grasps this foundation seems itself coherentist: Unless someone can distinguish in an account the form of the good from everything else, can survive all refutation, as if in a battle [] and can come through all of this with his account still intact, youll say that he does not know the good itself (7.534bc). We have witnessed this procedure, elenchus, throughout the Republic, starting with Cephalus and Polemarchus and Thrasymachus accounts of justice. We saw it most recently in the two accounts of the good that Socrates rejected earlier in Book VI. Socrates seems to suggest that what makes an account of x true is that it can survive the sort of cross-examination we have seen so far in the Republic. But his actual view, I think, is not that coherence constitutes the correctness of an account, but rather that coherence is the best criterion of correctness: an account is not made true by its having no internal inconsistencies and no false implications or entailments; instead, its consistency and coherence are good evidenceand perhaps the best evidencethat it is true. Readers familiar with Platos Euthyphro will find there a helpful example of this distinction between constitution and criterion. One of the Euthyphros main questions is whether the gods love holiness because it is holy or whether holiness is holy because the gods love it. That is, do the gods loving x make x holy or constitute xs holiness, so xs holiness is due to the external fact that the gods love it rather than some of its internal features? Or is the gods loving x simply good evidence that x is holy, their love for x being a criterion of xs being holy, but not what constitutes xs holiness? In short, is x loved because it is holy, or holy because it is loved? That an account of the good or any important concept is maximally coherent suggests that it is correct, but coherence is criterial rather than constitutive of its being true. What makes an account true is its connection to the Form of the good. 206 Platos Republic: An Introduction Socrates Hypothetical Method Before moving on, we should note how transparent Socrates has been in employing hypotheses in the Republic, reminding Glaucon and company of the conditional nature of any conclusions they draw from their hypotheses. For example, when offering the Opposition Principle as the basis for dividing the soul (4.436b), he remarks, let us hypothesize ( [hypothemenoi) that this is correct and carry on. But if we agree that it should ever be shown to be incorrect, all the consequences we have drawn from it will also be lost (4.437a). Socrates is reminding us that by employing hypotheses and analogies we are travelling on a less rigorous path, one that will give us a sense of what the good is but will not let us look on it directly. This should make sense, for even if Socrates is a genuine philosopher-king (though he claims otherwise), the rest of usGlaucon, Polemarchus, you, meare not, and we would be blinded by trying to look directly at the good, just as we would be blinded if we looked directly at the sun. So Socrates opts for the hypothetical, analogical method, which allows us to think about the good without understanding it. For that, dialectic is needed. Dialectic: Its No Game Socrates appeals to dialectic to distinguish genuine from counterfeit philosophers, as his response to the Third Wave requires of him. It also enriches his explanation of the negative view of philosophers so many Athenians have. The trouble is that a great evil comes from dialectic as it is currently practiced (7.537e), since the young people who practice it imitate Socrates method of intellectual cross-examination but misuse it by treating it as a kind of game of contradiction (7.539b). A genuine philosopher, who loves and reveres the truth, regards dialectic as the best means of getting at the truth and employs it in that spirit. But without reverence for the truth, dialectic becomes merely a game aimed at humiliating the bloviating pretender to knowledge and thus showing how clever its practitioner is. It is no wonder, then, that his fellow citizens regard Socrates as a bad influence on the young people who flock to him. Metaphors to Think by 207 Unsurprisingly, Socrates employs yet another metaphor to address the dangers of dialectic when it is not practiced with the love of truth. Imagine a bright young person brought up surrounded by much wealth and many flatterers [] who finds out, when he has become a man, that he is not the child of his professed parents and that he cannot discover his real ones (7.538a). This turns the young persons world upside down: core beliefs about who they are turn out to be false, they regard their adoptive parents as liars and no longer live as they were raised to do. This is what it is like to be a young person whose core moral beliefs are challenged. A person who is properly raised will, like Glaucon and Adeimantus, believe that the just life is happier, that they ought to be motivated by what is fine and noble rather than by narrow self-interest, but they do not know why the just life is happier or what the fine and noble really is. Dialectic as practiced by counterfeit philosophers shakes him from his convictions, and makes him believe that the fine is no more fine than shameful, and the same with the just, the good, and the things he honored most (7.538d). It induces a kind of intellectual and moral vertigo: values and ways of life that seemed so certain now seem flimsy and evanescent. Improperly deployed, dialectic turns young people into relativists or nihilists who think of traditional moral virtues such as justice as shams in much the same way Thrasymachus did back in Book I: as tools clever people use to dupe simpletons like the unknowing orphan until the scales fall from their eyes. That so many of Platos dialogues end without discovering the nature of the virtue in questionthat is, in aporia: difficulty or befuddlementprobably does not help, either. Rather than thinking that eliminating wrong accounts is a kind of progress, the clever game-player thinks he is shown that there is no answer. Socrates thinks that few young people are sufficiently orderly and steady by nature (7.539d) to practice dialectic properly; instead of being willing to engage in discussion in order to look for the truth, the bright young person plays at contradiction for sport. (7.539c) They will imitate and thus internalize the wrong models (7.539bc), which echoes the concerns Socrates raised when discussing how and why the storytellers needed to be supervised. Thus in the advanced education for would-be philosopher-queens and -kings that we will look at after discussing the Cave Analogy, students are not trained in dialectic until they reach the age of thirty (7.537d). 208 Platos Republic: An Introduction So dialectic is no game. It is dangerous if practiced without a love of truth, capable of doing real damage to both its practitioner and its victims. But it also promises great cognitive benefit, as it is the genuine philosophers tool par excellence, a tool enabling full understanding. This understanding goes far beyond the kind of understanding Socrates analogies can yield, which Glaucon claims at the close of Book VI. He understands () Understanding (), but he does not Understand it. Some Suggestions for Further Reading Readers interested in exploring the Sun and Line analogies in greater depth and detail might try Nicholas Denyer, Sun and Line: The Role of the Good, in The Cambridge Companion to Platos Republic, ed. by G. R. F. Ferrari (New York: Cambridge University Press, 2007), https://doi. org/10.1017/ccol0521839637, pp. 284309, or Chapter 10 (Understanding the Good: Sun, Line, and Cave) of Julia Annas, An Introduction to Platos Republic (New York: Oxford University Press, 1981), pp. 24271, which is reprinted in Platos Republic: Critical Essays, ed. by R. Kraut (Lanham, MD: Rowman & Littlefield, 1997), pp. 14368. Readers interested in the wrinkle in the Line (that segments b and c have the same length) might first see Chapter 9 (esp. pp. 2034) of R. C. Cross and A. D. Woozley, Platos Republic: A Philosophical Commentary (New York: St. Martins Press, 1964), pp. 196230. Readers interested in exploring the distinction between coherentism and foundationalism might start with the first section of Erik Olssons Coherentist Theories of Epistemic Justification, in the Stanford Encyclopedia of Philosophy (https://plato.stanford.edu/entries/ justep-coherence/). Susan Haack, Evidence and Inquiry: A Pragmatist Reconstruction of Epistemology, 2nd ed. (Amherst, NY: Prometheus Books, 2009) seeks a middle ground between the two, which she dubs Foundherentism. William Alston, Epistemic Justification: Essays in the Theory of Knowledge (Ithaca: Cornell University Press, 1989) contains excellent essays on justification by one of the leading epistemologists of the last century. Markus Maurer, drawing of Platos Allegory of the Cave with Wikipedias logo as the sun (2015). Photograph by Crystallizedcarbon (2015), Wikimedia, CC BY-SA 3.0, https://commons.wikimedia. org/wiki/File:Plato_Cave_Wikipedia.gif#/media/File:Plato_Cave_ Wikipedia.gif 11. The Allegory of the Cave: Book VII The Allegory of the Cave is arguably the most famous part of the Republic. Although it is clearly related to the Sun and Divided Line analogies (indeed, Socrates explicitly connects the Cave and the Sun at 7.517bc), Plato marks its special status by opening Book VII with it, emphasizing its importance typographically, so to speak (he will do much the same thing in Book IX with the discussion of the tyrannical soul). Although an allegory is sometimes defined as a symbolic narrative that can be interpreted as having a hidden meaning, Plato is not cagey about the Cave Allegorys meaning: it is about the effect of education ( [paideia]) and the lack of it on our nature (7.514a). Given how visual the allegory is, many readers will find it helpful to draw themselves a diagram of it. Education, the Allegorys topic, is not what most people think it is, says Plato: it is not putting knowledge into souls that lack it (7.518b). Though education sometimes requires that kind of transmission of knowledge from teacher to student, this is not its essence, which instead is turning the whole soul (7.518d)turning it around, ultimately toward the Form of the good. Education as turning around is a powerful metaphor, capturing the way in which learning involves gaining new perspectives, seeing everyday things and events from new points of view. Everyone, Plato insists, is capable of education in this sense (7.518c). But not everyone is capable of making it out of the Cave into the intelligible world of the Forms, just as not everyone is capable of winning a Nobel Prize in Physics or an Olympic medal in Figure Skating. Nonetheless, Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.11 212 Platos Republic: An Introduction everyone has the capacity to be educated, to turn their soul from what is less real toward what is more real. Stages in the Cave Allegory I count six distinct stages in the Cave Allegory. While such divisions are always prey to arbitrariness and subjective preference, I hope that the division I offer sheds light on what Plato is up to here. In the first stage, the caves residents are prisoners, chained to their seats and unable to move not only their bodies butcruciallytheir heads. They can only look straight ahead, and thus have only one perspective on what they see on the caves wall. What they see are the shadows of a sort of puppet show taking place behind them, with shadows cast by the light of a fire. The puppets are various artifacts: statues of people and other animals, made out of stone, wood, and every material (7.514b). The prisoners watch the shadow-play, ignorant of the true nature of what they see: they believe that the truth is nothing other than the shadows of those artifacts (7.515c). They take for reality what is a mere image of it. Some readers will have already noticed that Stage One is parallel to the lowest section of the Divided Line (segment a), the objects of which are images and shadows. In the second stage, one of the prisoners is freed from their bonds. Plato does not tell us by whom or how; we are left to wonder whether the prisoner was saved by human agency or by the natural decay of their fetters. There is reason to think it is the former, since the freed prisoner is suddenly compelled to stand up, turn his head, walk, and look up toward the light (7.515c), and somebody else seems to be doing the compelling. This is not the only time Plato connects education with compulsion, with being forced to turn ones head and gain a new perspective. Nor is it the only time when the head-turning that constitutes education will be painful. When the freed prisoner is forced to look at the shadow-casting fire that until this moment they were unaware of, they will be pained and dazzled and unable to see the things whose shadows they had seen before (7.515c). They will probably not like the experience at all, even though in being freed from their fetters they are thereby cured of [their] ignorance (7.515c)not merely freed but cured, as if ignorance is a disease. It is a comfortable disease, to borrow a The Allegory of the Cave 213 phrase from e. e. cummings, for it is a world the cave-dweller is familiar with and comfortable in. Turned around and out of their comfort zone, they are unable to recognize the shadow-casting puppets, despite their skill at recognizing the shadows the puppets cast on the wall. Although the artifacts are, like any sensible particulars, not fully real, they are more real than the shadows they cast. Thus in looking at the shadow-casting artifacts the freed prisoner is a bit closer to the things that are and is turned towards things that are more (7.515d); this is the existential sense of the verb to be that we distinguished earlier: the prisoner is closer to the things that are realthat existand indeed is coming closer to the things that are fully real: the Forms. While not everyone is capable of making it out of the Cave, Plato thinks that everyone is capable of being turned from the shadows to the shadow-casting artifactsof moving from the lowest segment (segment a) of the Divided Line to the next highest (segment b), the realm of belief proper. Screenstelevision screens, phone screens, computer screensare the Cave walls of today. When we uncritically accept the words and images we see there, we are like the chained prisoners. But if we turn and look at the sources of the information flickering before us, we might recognize that the information is distorted by bias and ulterior motive. Unlike the Caves puppeteers, who do not seem to derive any benefit from their shadow-casting, the shadow-casters of our age typically do derive some benefit, and frequently their power depends upon our remaining chained, accepting the images they project before us, and believing that the truth is nothing other than the shadows (7.515e). While being turned around is good for us, we often do not initially like it. But there is also a danger that in being turned around we will reject information we disagree with and take its source to be biased. Clearly, many sources are biased, but if we reject every artifact that comes from a puppeteer we do not like, it is not clear that we are any better off than we were before we turned to look. In fact, we might be worse off if we fall prey to the belief that critical thinking involves (merely) rejecting perhaps as fake newsanything emanating from sources we identify as liberal or conservative or whatever. Education, in the end, is not just any kind of turning around; it requires that the student be turned the right way (7.518). 214 Platos Republic: An Introduction In the third stage we again see the role that compulsion plays in the Cave Allegory, for an unnamed, unidentified someone will drag [the freed prisoner] away from there by force, up the rough, steep path (7.515e). Although Socrates devotes just one sentence to the third stage, what he says later in Book VII indicates that this rough, steep path symbolizes the formal education that potential philosopherrulers receive. This four-subject education is the basis of the quadrivium of classical liberal education, the sort of education suitable to a free person. It is education centered on number: arithmetic (number itself), geometry (number in space), harmonics or music theory (number in time), and physics or astronomy (number in space and time). All these number-based subjects lead the soul and turn it around towards the study of that which is (7.524e), which ultimately is the Form of the good. While there are certainly practical applications of these subjects, the would-be philosopher-queens and -kings study them not like tradesmen and retailers [ but] for ease in turning the soul around, away from becoming and towards truth and being (7.525c). These disciplines prepare would-be philosophers not for craft-based careers in the sensible world, where they might be bakers or cobblers or doctors (although it will prepare them to be generals, as they are the citys guardians), but rather for citizenship in the intelligible world. They will learn to think abstractly, grasping essences and integrating Forms, which is presumably why studying geometry tends to make it easier to see the Form of the good (7.526d). As the way out of the Cave, these subjects are merely preludes to [] the song that dialectic sings (7.531d32a), and that is a tune that is sung only in the intellectual sunlight of the intelligible world outside of the Cave. In stage four, the prisoner is not just freed from their fetters but has made it out of the Cave into the intelligible world above, which corresponds to the top half of the Divided Line (segments c and d). Looking at the fire in the cave hurt their eyes, and they find emerging into the sunlight painful, just as a mid-afternoon moviegoer who leaves a dark theater is pained by the bright parking lot outside. At first, they will only be able to look at shadows of the objects in the world above, here cast by the light of the sun rather than the fire, or their reflections in water, or look at the objects at night. Just as the shadows on the cave wall were mere copies of the artifacts held before the fire, those artifacts are The Allegory of the Cave 215 mere copies of the Forms, which are the things themselves (7.516a). Although Socrates does not say, we can assume that there is one Form for each of the many particular objects in the cave. Whether there is one treethe Form of treeness itselfor one oak tree, one maple tree, one white pine, one yellow pine, etc. is an interesting question to ponder, but it is not one we need to answer to understand the Cave Allegory or the Republic as a whole. At stage five, the former cave dweller is able to look directly at the sun, not images of it in water or some alien place, but the sun itself, in its own place, and be able to study it (7.516b). Presumably not everyone who makes it out of the Cave is able to do this. Mathematicians and scientists study the Forms relevant to their disciplines, but they do not see other Forms or how the Forms they contemplate are related to these other Forms, and they certainly do not see the Form of the goodthat vision is reserved for genuine philosophers, and there are very few of them. So presumably the fourth stage in the Cave Allegory corresponds to Thought on the Divided Line, while the fifth stage is where Understanding operates. In stage six, the sun-contemplating philosopher first thinks back on his life in the cave, and reflecting on what passed for wisdom there (7.516c), smiles ruefully and feels pity for the others still trapped in their ignorance, who know only the shadows on the wall or the artifacts casting them. What would happen if the enlightened philosopher descended into the cave? They will not be greeted as a returning, liberating hero, Socrates thinks. The denizens of the dark world below will first think the returning philosopher a fool: until their eyes, used to the bright light of the intelligible world, have adjusted to the darkness of the cave, they will be unable to recognize the shadows or the puppets. Like the ship owner who thinks the true captain is a useless stargazer (6.489c), the cave dwellers will think the enlightened philosopher a fool who has ruined their eyesight (not to mention his economic prospects) by looking too long at the sun. But if they persist and try to free the prisoners and turn them toward the firelight or drag those who are able out of the cave, they will think their liberator is worse than useless: they will think them dangerous, and if they could somehow get their hands on him [] they [would] kill him (7.517a). 216 Platos Republic: An Introduction Plato does his readers a good turn by having Socrates explicitly connect the Sun and Cave metaphors (7.5157bc), but he leaves the task of fitting together the Divided Line and Cave to us. Fortunately, connecting them is fairly straightforward, as we have already seen. The shadows on the Caves wall correspond to the images seen at the Divided Lines lowest section (segment a), the realm of Imaging. The shadow-casting puppets held before the fire correspond to the originals of [the Lines] images (6.510a), in segment b. Just as the shadows are copies of the originating artifacts, these artifacts, which are at home in the Visible World, are in turn copies of the Forms, which of course reside in the Intelligible World (section c). Plato is not suggesting that the images, shadows, and reflections are not real, but rather that they are less real than the originals they are images of. This has a lot of intuitive appeal: I can create a shadow of my hand by interposing it between my desk and lamp, but the shadow cast seems less real than my hand in at least a couple of ways. First, while my hand is a threedimensional object, the shadow is only two-dimensional, lacking the dimension of depth. Second, the shadow depends for its existence on the presence of my hand (and on the presence of the third thing that features in the Sun Analogy: light). My hand still exists when I turn off my desk lamp or move it out of the lamps range, but the shadow no longer exists. Shadows, reflections in mirrors and water, etc.the stuff of segment a of the Lineare ephemeral. They are not unreal my seeing the shadow is not an optical illusion: there is something there, just something whose existence is thinner and flimsier than the objects at the Lines second section (segment b). Nowand heres the metaphysically important pointjust as the shadows and reflections are copies of what seem to be independently existing objects, these objects themselves are copies of the Forms they instantiate. The bed the carpenter makes, Socrates argues in Book X, is something which is like that which is (10.597a). The second is is the is of existence: the built bed is like what is real, what fully exists. Its resembling the Form of bedness is what makes it a bed and not a table, but, just as Van Goghs paintings of his bed at Arles are copies of the bed he slept in, so too is that bed a copy of the Form. Thus Platos metaphysical point can be put as a ratio, image: original :: original: Form. The Allegory of the Cave 217 There is much that Plato leaves unsaid about the Cave. Who first frees the prisoner? Who drags them up and out of the cave? Who are the puppeteers? What, if any, benefit do they derive from keeping the prisoners occupied with shadows? Glaucon says toward the outset that these are strange prisoners, to which Socrates replies, they are like us (7.515a), so with a bit of imagination we can fill in some of these blank spots. Trouble in Paradise: The Powers Argument Casts a Shadow on the Cave Allegory There is a problem lurking in the background of the Cave Allegory that should be brought to the forefront and addressed. Indeed, all three of the key analogiesthe Sun, the Divided Line, and the Caveare analogical or metaphorical accounts of two distinct worlds or realms: the intelligible world, where the Forms reside, and the visible world, home to spatiotemporal particulars. The Powers Argument was supposed to provide some reason for believing in Platos two-worlds metaphysics and indeed for taking the Metaphysical Elevator to the fourth floor, where the Forms are not just real but are more real than the particulars that instantiate them. But we have seen that that the Powers Argument is logically invalid, since its conclusions could be false even if its premises are true, and even if its logical problems could be fixed, it would still not provide a good reason to accept Platos two-worlds metaphysics, given the implausibility of belief and knowledge having distinct objects. Presumably what Socrates says about agreed-to hypotheses that prove to be false goes for arguments, as well: that if it should ever be shown to be incorrect, all the consequences we have drawn from it will also be lost (4.437a). Since the Sun, Divided Line, and Cave Analogies all require the distinction between the Visible and the Intelligible Worlds, they are infected, perhaps fatally, by the failure of the Powers Argument. Of course, Platos two-world metaphysics could still be correct, since the conclusion of an unsound argument can still be true. But unsound arguments do not justify belief in their conclusions. What should we make of the major analogies of Books VI and VII in light of the failure of the Powers Argument? One option is to proceed in a hypothetical or conditional way: if these are the two worlds, then here is how they differ. 218 Platos Republic: An Introduction Given the hypothetical nature of Socrates procedure in the Republic, this is not a bad way to go. Another option is to interpret the two worlds non-literally but metaphorically, which fits well with the prevalence of metaphor in the Republic. On this view, the two worlds are ways of thinking about or conceptualizing reality rather than assertions about the nature of reality itself. And perhaps this is how the two-worlds metaphysics should be interpreted even if the Powers Argument were sound: think of the Forms populating the intelligible realm (and that realm itself) as useful fictions. This metaphysically more cautious view would appeal to fans of Ockhams Razor. A problem with the metaphorical interpretation, however, is that Plato himself seems to take the two worlds literally: there are these two things [i.e., the Form of the good and the sun], one sovereign of the intelligible kind and place, the other of the visible (6.509d). Plato thinks of these as places, which suggests their reality. Although the word being translated as place ( [topos], whence the English word topographical) could mean realm in a non-physical sense, it is difficult to think that Plato intends his talk of the Forms and the intelligible realm to be taken only metaphorically. Still, for readers bothered by the failure of the Powers Argument, this may be the best interpretation, even if it is not Platos. After all, we can still distinguish Understanding from Thought, the two kinds of cognition at work in the intelligible realm, without being realists about the Forms. Even if we take Platos Metaphysical Elevator only to the second floor, we can still distinguish people who grasp the essence of a perhaps narrow range of things from people who do not merely grasp more essences but also see connections between them. Integrative thinking is one of the hallmarks of dialectic, and one can prize that capacity while at the same time denying that the Forms existent mind-independently. Even Socrates himself is agnostic in the literal sense of not knowingabout the metaphysical status of the Forms and the intelligible realm: Whether its true or not, only the god knows (7.517b). He seems to believe that the Forms are real, but perhaps this remark is Platos way of indicating that he is aware of the Powers Arguments shortcomings: Socrates himself does not think he has proven the arguments conclusion. Early in Book X he recounts his usual procedure, which is to hypothesize a single form in connection with each of the many things to which we apply the same name (10.596a). The Allegory of the Cave 219 So he seems aware of the hypothetical, mathematician-like nature of his investigation. If Socrates can live with this sort of uncertainty, perhaps readers can as well. Food for thought. But it is now time to turn to another worry about the Cave Allegory, the enlightened philosophers return to the world below. Going Back Down into the Cave (7.519b520b) Having been fully liberated from the dark, smoky world of the Cave, the enlightened philosophers are in no hurry to return. Readers will remember that the problem Socrates faces in responding to the Third Waveand it is worth remembering that the Sun, Divided Line, and Cave analogies are all part of that responseis that in the actual world, political power and philosophy are separated, with philosophers as uninterested in participating in the messy world of politics and government as those in power are in studying metaphysics and epistemology. The solution, both to the ideal citys real possibility and to individual and communal happiness, is that these philosophers and political leaders be forcibly prevented from pursuing their own interests exclusively. Somehow, political power and philosophy [must be made to] entirely coincide (5.473cd). The philosophers would prefer to remain in the sunlit world above, contemplating the Forms. But possessing knowledge of the good, they and they alone are capable of governing. They have been compelled to ascend to the sunlit, intelligible world above; is it fair to compel them to go back down to the dark, smoky cave, the visible world below? There is a substantive philosophical problem for Socrates view that the just life is happier than the unjust life, an issue that Plato does not notice or at least does not remark upon. But before investigating that, we should attend briefly to one of the Republics most gratifying literary delights. The issue before us is compelling the enlightened philosophers to go back down into the cave to govern it. The Greek word at issue is (katabainein), to go down. If you turn to the Republics first page, you will see that Socrates first words, the very first words of the Republic, are I went down (1.327a). The Greek there is (katebn), the first-person singular form of in the aorist 220 Platos Republic: An Introduction (past) tense. The implication is that we are all cave-dwellers and that Socrates going down to the Piraeus is like the enlightened philosophers going back down into the cave, where we muck about in the dark as we look for justice. It is no wonder that, having discovered the other three political virtues (wisdom, courage, moderation), Socrates finds justice hard to locate at first: the place seems to be impenetrable and full of shadows [] dark and hard to search (4.432c). The conversation that is the Republic, then, takes place in the Cave, where we contend about the shadows of justice or the statues of which they are the shadows (7.517d). Although Plato could have had Socrates just say this simply and directly, it is more powerful and more aesthetically pleasing for readers to see this for themselves. Although some readers will yawn, others will be delighted at Platos literary artistry, and perhaps will be able to understand more fully why some people devote their lives to understanding and appreciating his philosophical thought and literary craft and the way he integrates them. Now on to the substantive philosophical question of the enlightened philosophers return to the cave. An important point to grasp is that the liberated philosopher is not on a mission of liberation, at least not complete liberation, since on Platos view not everyone is capable of making it out of the cave. As we have noted several times already, he thinks that the majority cannot be philosophic (6.494a). The returning enlightened philosopher will free whom he can, dragging those who are able to follow up the rough, steep path (7.515e), but their main task is to govern in the Caveto guard and care for the others (7.520a). We know they will not be received well, but if through some chance event or divine intervention (6.499b) they are able to take charge of the cave, they will govern well, since they have the virtue needed to do so: political wisdom. Even so, the philosophers do not want to return to the Cave, and interestingly enough, Plato takes this as a plus: A city whose prospective rulers are least eager to rule must of necessity be most free from civil war, whereas a city with the opposite kind of rulers is governed in the opposite way (7.520d). Since it is those who are not lovers of ruling who must rule (7.521b), the returning philosophers reluctance counts in favor of their doing so. So why do the philosophers descend into the cave and do what they do not really want to do? Just as they were compelled to ascend out of the The Allegory of the Cave 221 cave, they are compelled to descend into it, but the compulsion in the two cases is different. They were physically dragged up, at least metaphorically speaking, but they are not physically dragged back down. It is no accident that their being compelled upward would be metaphorically physical, since our particular individual bodies belong in the visible realm of particulars, while our souls, by contrast, are not physical, so there is nothing to drag. Their being compelled downward is mental or psychic, but it is not the irrational or non-rational compulsion that consists in brainwashing or advertising by people who seek to cause us to pursue ends they have chosen for us. Instead, the enlightened philosopher is compelled to return by rational persuasion. If one recognizes that an argument is soundthat its conclusion must be true if its premises are true and that its premises are in fact trueone is rationally compelled to accept the conclusion. This is not as a matter of internal or external causation, but rather of rational compulsion: the force of rational persuasion. So what is the argument that the enlightened philosophers should find so compelling? As I hinted earlier, Socrates does not argue that any enlightened philosopher has a duty to descend to the cave and govern. Instead, only those whose enlightenment results from the citys having educated them have that duty. What grows of its own accord and owes no debt for its upbringing, he argues, has justice on its side when it is not keen to pay anyone for that upbringing (7.520b), where the currency of repayment is governing. It might be noble of an accidentally- or divinely-self-enlightened philosopher to do what they do not really want to do and descend into the cave, but this is not a requirement of justice: they would not act wrongly were they to remain above, pursuing their philosophical interests. But a philosopher educated by the city has a duty of reciprocity and gratitude to descend and govern. We should note that Plato here shows that he is not a consequentialist about morality. We can assume that the consequences of the philosophers descending would be better, all things considered, than the consequences of their remaining in the intelligible world above. If we take the good they would do by governing, which is presumably substantial, since there can be no real happiness for the citizens if philosophers do not rule (5.473e), and subtract from it the personal cost to them of sacrificing their own preferences for the good of the group, the net consequences of descending would still be overall better than those of not descending. 222 Platos Republic: An Introduction But this fact alone is not sufficient to generate a duty for the enlightened philosopher to descend and govern. Were they to go down into the cave, they would be going beyond the call of dutygoing down would be supererogatory, as philosophers say. Supererogatory actions are praiseworthy to perform, but not blameworthy to omit. Donating a kidney to a stranger is, other things being equal, praiseworthy, but my not doing this is not blameworthy: I do not act unjustly if I keep both of my kidneys. (Of course, if I have promised to donate the kidney and the stranger has relied on my promise, then other things are not equal, and the moral situation has changed considerably.) Actions required by justice are different: failure to perform them is blameworthy, and, other things being equal, performing them is not praiseworthy. Special circumstances are required for refraining from violence to be praiseworthy, as envisioned in a Sopranos episode when Tony, a violenceprone mafioso, forgoes killing his daughters sexually predatory soccer coach and lets the police deal with it. I didnt hurt nobody today, Tony drunkenly tells his wife, and for him, this is suitably praiseworthy.1 For the rest of us, not killing people who bother us or whom we regard as moral reprobates is what is minimally expected, and there is no praise for doing what we ought to be doing. So not just any enlightened philosopher, but only the enlightened philosopher who owes their enlightenment to the education that the city has provided for them, has a duty to go down into the cave and govern. Here is the argument Socrates gives them: We have made you kings in our city and leaders of the swarm, as it were, both for yourselves and for the rest of the city. You are better and more completely educated than the others and are better able to share in both types of life. Therefore each of you must go down to live in the common dwelling place of the others and grow accustomed to seeing in the dark. When you are used to it, youll see vastly better than the people there. And because you have seen the truth about fine, just, and good things, youll know each image for what it is and also that of which it is the image. Thus, for you and for us, the city will be governed, not like the majority of cities nowadays, by people who fight over shadows and struggle against one another in order to rule [] but by people who are awake rather than dreaming (7.520bc) 1 The Sopranos, Season 1, Episode 9, Boca, dir. by Andy Wolk (HBO, 1999). The Allegory of the Cave 223 This is an interesting argument, and it certainly has a lot of intuitive appeal. There is something compelling, after all, about obligations of gratitude: if you have gone out of your way to benefit me, I seem to incur a debt of gratitude. What it takes to repay that debt varies with the circumstances: often, a simple thank you! is all that is required, but other timesas in the present casemore is required. Here, Socrates argues that, as a matter of justice, the enlightened philosophers must (temporarily, at least) give up the life they prefera philosophical life devoted to contemplating the Formsfor a life of political action. (These are the both types of life referred to in the quotation above.) Plausible though the argument is, there is something troubling about duties of gratitude, even when the benefit to be reciprocated was bestowed intentionally, for the sake of the beneficiary. The worry is that one can go around obligating others to do good turns for oneself by doing good turns for them. If I show up unbidden and start harvesting your wheat for you, does my supererogatory act really bind you to do the same for me? Many of us would feel obligated to reciprocate, but the issue is not the psychological one about our feelings but rather the philosophical, normative one about our duties. Consider how your views would change if the helpful harvester helped not primarily because he wanted to benefit you, but because he needed your help harvesting his large wheat field, and, knowing you to be a nice person but not wanting to ask for your help, decided that the best way to get you to help him was to help you. I suspect you would feel a bit manipulated. And suppose that your neighbor harvested your wheat when you were away in town on Saturday, without asking if you needed or wanted their help. They would have imposed this benefit on you, without your consent. Your supposed duty to return the favor would look flimsier and flimsier. The trouble with Socrates argument is that the citys actions in educating the philosopher too closely resemble the helpful neighbor harvesting your wheat. Remember that the would-be rulers are compelled to leave the cave: someone dragged him away from there by force, up the rough, steep path, and did not let him go until he had dragged him into the sunlight (7.515e). The benefit has been bestowed and received non-voluntarily, which surely makes a difference to whether there is a duty of gratitude to reciprocate. In addition, Socrates misspeaks when he claims that the philosophers were educated both for [them]selves 224 Platos Republic: An Introduction and for the rest of the city (7.520b). Any benefit the philosophers personally receive is foreseen, but not intended. Given the strong communitarian thrust of the ideal city, it is clear that the education is not primarily intended for the philosophers benefit but rather for the citys; any benefit the individual philosopher receives is a side effect or by-product. But even if Socrates argument for a duty to return is sound, there are disquieting implications for his view that the just life is happier than the unjust life, that justice benefits its possessor. Thrasymachus insisted that while justice benefits others it is always bad for its possessor: being just and acting justly makes one worse off in the long run. Thus Thrasymachus sees a wedge between what is good (or right) and what is good for me. Consider the situation of the enlightened philosopher. They would strongly prefer to remain in the Intelligible World, basking in its sunlight and contemplating the Forms. They will return because, being just, they will do what justice requires of them, even when they do not want to do it. But make no mistake about it, they do not want to return, and ruling is something compulsory (7.520e), not enjoyable in itself as doing philosophy is. And notice that ruling does not really fit into any of the three categories of goodness that Glaucon articulates at the beginning of Book II. While ruling seems at first to belong to the category of goods that are onerous but beneficial (2.357c), upon reflection we can see that it does not really fit there, since this mixed category contains goods that are onerous but beneficial to us (my emphasis). Few people enjoy flossing their teeth, but those who do this regularly derive a benefit and presumably decide that on the whole flossing is worth it: but its value is extrinsic and instrumental, not intrinsic. But imagine if flossing benefited not the flosser but someone else. This seems to be the position of the enlightened philosopher. They return to the cave to govern, but they would rather not, since they would be personally better off ignoring the demands of justice. When Glaucon worries that justice is making them live a worse life when they could live a better one (7.519d), Socrates does not reply that they are better off acting justly; instead, he reprises the response he made to Adeimantus at the beginning of Book IV: his concern is not to make any class [or particular citizens] The Allegory of the Cave 225 in the city outstandingly happy but to contrive to spread happiness throughout the city (7.519e; compare 4.419a and 5.466a), which concedes the assessment underlying Glaucons question. The philosophers return benefits the caves residents, since there can be no happiness, either public or private in any city not governed by a philosopher-king or -queen (5.473e). But returning does not benefit them personally, and that is the real issue here. Socrates seems to be conceding that Thrasymachus is right after all: justice benefits someone else, not its possessor. Even if the overall consequences of the philosophers returning were better than the consequences of their remaining above, their return would not benefit them. So it looks like justice does not benefit its possessor: leading a good life seems to come at the cost of having a good life. Thus it seems that the philosophers situation is analogous to the far-fetched scenario in which flossing does not benefit the flosser but somehow benefits others. It would be a mistake to think that even in this scenario I would have no self-interested reasons for flossing. If there is a community norm that everyone should floss, my flossing would help sustain and promote this norm (and thus indirectly contribute to the benefit adherence to the norm produces) and encourage others to do so as well. If this is the case, then my flossing would benefit me indirectly. In doing my part to uphold norms that benefit the community, the burden of compliance might be counter-balanced by the benefit received. The same might be said for the returning philosopher, who lives a better life in a well-governed city than they do in the poorly governed city of the Shelter from the Storm analogy, which we considered in the last chapter. Although they would rather not descend, perhaps the philosophers doing so really does benefit them when we look at the big picture. So perhaps Socrates does not give away the game to Thrasymachus after all. Even though the philosophers return seems altruisticthey return to labor in politics and rule for the citys sake (7.540b) rather than their own, they might in fact benefit by their return. Though the citys good is the outcome they intend, they can perhaps foresee that they will benefit too. A worry remains, though: in the imaginary scenario in which flossing benefits others, it seems unlikely that my not flossing will have bad 226 Platos Republic: An Introduction consequences so long as enough of my fellow citizens floss regularly. Or, to take a less far-fetched example, I might reason that while I enjoy National Public Radio, I can still receive this benefit without bearing my share of the burden, since NPRs not receiving $100 from me will not cause them to close up shop. It seems to be in my self-interest to be a free-rider, benefiting from the good behavior of others while not burdening myself with doing my share. The ethics of Immanuel Kant rules out such free-riding behavior: if everyones acting on the maxim or principle I plan to act on would make it impossible for me to act on it, then my acting on it is wrong. But Kant did not share Socrates view that doing the right thing makes me better off all things considered: the demands of morality are frequently at odds with those of self-interest and happiness. Now perhaps free-riding would not even tempt the fully just philosopher, who takes their turn at ruling without complaint. But the self-interested Thrasymachan, who is vicious but clever (7.519a), is unlikely to be persuaded: the philosopher would clearly be better off if they missed a turn every once in a while, if they called in sick when they really wanted a day of metaphysical sun-bathing. And things look even worse for the view that the just life is happier if we bear in mind the lives Socrates is to compare to settle the question of which life is happier: a just person who appears unjust versus an unjust person who appears just. The philosopher who does not go back down to the cave would be unjust, but under the terms agreed to they would not appear to be so: their free-riding would have to go unnoticed and thus would not undermine the norms governing the small community of philosophers, so their not going back down to the cave to rule benefits them without the negative effect on norms of justice. These are some of the issues readers will want to keep in mind as we explore Books VIII and IX, where Socrates resumes his investigation of the Republics second question. In Book VII, though, he does not seem to notice themor if he does, he gives no explicit indication of this. The Allegory of the Cave 227 Some Suggestions for Further Reading There is a large literature on Platos Allegory of the Cave. Readers interested in the thought of Martin Heidegger will want to see The Essence of Truth, trans. by Ted Sadler (New York: Contiuum Books, 2002). For an account more in keeping with the style and concerns of contemporary Anglophone philosophy, readers might turn to Chapter 10 (Understanding the Good: Sun, Line, and Cave) of Julia Annas, An Introduction to Platos Republic (New York: Oxford University Press, 1981), pp. 24371, reprinted in Platos Republic: Critical Essays, ed. by Richard Kraut (Lanham, MD: Rowman & Littlefield, 1997), pp. 14368. Readers with a taste for serious cinema and an interest in the Cave Allegory will certainly want to watch The Conformist, dir. by Bernardo Bertolucci (Paramount Pictures, 1970), about a young fascist tasked with assassinating his former philosophy professor. The film is rife with Platonic imagery as well as a cinematically brilliant discussion of the Cave. Interested readers can find an animated version of the Cave Allegory on YouTube, narrated by the great Orson Welles, at https://www.youtube. com/watch?v=_jmJGBJRlUQ. Readers interested in the enlightened philosophers descent back into the Cave should see Richard Kraut, Return to the Cave: Republic 519521, in Plato 2: Ethics, Politics, Religion, and the Soul, ed. by Gail Fine (New York: Oxford University Press, 1999), pp. 23554. Readers interested in gratitude as a basis for duties of justice might start with Chapter 7 of A. John Simmons, Moral Principles and Political Obligations (Princeton: Princeton University Press, 1979), pp. 15690. M. A. Barth, Return of Peisistratus to Athens with the False Minerva (1838). Photograph by Patna (2018), Wikimedia, Public Domain, https:// commons.wikimedia.org/wiki/File:Return_of_Peisistratus_to_Athens_ with_the_false_Minerva.jpg#/media/File:Return_of_Peisistratus_to_ Athens_with_the_false_Minerva.jpg 12. The Decline and Fall of the Ideal City-Soul: Books VIIIIX Having addressed the Three Waves to the satisfaction of Glaucon and company, Socrates picks up where he left off at the end of Book IV, enquir[ing] whether it is more profitable to act justly, live in a fine way, and be just [] or to act unjustly and be unjust (4.444e45a). To settle this question, he plans to trace the decay of the ideal, just city and soul into their unjust opposites. This is as we should expect, given the city-soul (polis-psych) analogy that guides him in answering the Republics two main questions, What is justice? and Is the just life happier than the unjust life? There are five mirroring pairs here, with each city corresponding to a kind of soul, both organized and governed in the same way and having a distinctive good that it pursues. This is a story of decay, of psychic and political disease rather than mere change. Matters go from best to worst as the aristocratic soul and cityso called because the best (ariston) part of the city and the soul has power (kratos)gives way to the honor-loving timocracy, which in turn degenerates into the money-loving oligarchy, and this to freedom-loving democracy until the worst psychic and political arrangement is reached: tyranny. Ultimately, Socrates will compare the aristocratic and the tyrannical souls as he answers the Republics second question. There is a lot going on here, so our discussion will be selective. Of course we will want to attend to which part of the city or soul is in charge and what end or goal each pursues as good in itself. We will Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.12 230 Platos Republic: An Introduction also attend to the transvaluation of valuesto the ways in which virtues become vices and vices virtuesin this long, dark night of the soul and city, noting both the internal and external causes of decay. A common thread throughout the discussion is the role played by changes to the educational program developed earlier in Books II and III. The Aristocratic City and Soul (8.543a547c) Philosophers govern the aristocratic city and reason governs the aristocratic soul. The former is the paradigm of political justice, the latter of personal justicewhich is what Plato most cares about in the Republic, a fact that is easy to forget, given the attention lavished on citybuilding. It is interesting that Socrates does not make explicit what the best and the worst cities and souls take the good to behere by the good he means not the Form of the good but rather [the] single goal at which all their actions, public and private, inevitably aim (7.519c). It is their telos, their end or overarching aim, the goal that organizes their thought and action. It is by reference to this good that their activities make sense. There are a few plausible candidates for the aristocratic citys and souls good, and I suggest that we take justice, the outstanding virtue in the Republic, to be their good. With each part of the city or soul performing its role well, the city and soul will function well and flourish and thrive: it will be happy. By this point we have a pretty good idea of what the aristocratic city and soul are like, given the care with which Socrates has described them. So what causes the decay of these ideals? Why does aristocracy decay into the second-best arrangement, timocracy? Socrates answer is a bit of a downer. It is not that aristocracy does decay but rather that it must: everything that comes into being must decay (8.546a). Perhaps this is a prescient nod to a moral analog of the law of entropy. Depressing though it is, it should come as no surprise, for if the ideal, aristocratic polis were ever realized, it would be realized in the visible, sensible world. This is the world of coming-to-be and passing-away, the world of becoming rather than the world of being, where the changeless Forms reside. Decay is inescapable in the sensible world of concrete particulars, which are ceaselessly coming to be and passing away. The Decline and Fall of the Ideal City-Soul 231 The initial cause is somewhat surprising, though: the guardians, as wise and mathematically gifted as they are, miscalculate the perfect number (8.546b) that should govern the reproductive schedule of the guardians. It is not their fault, really. They are bringing calculation ( [logismos]), the heart of the first subject of advanced study for would-be rulers, to bear upon sense perception (8.546b), and one of the abiding lessons of the Third Wave is that while we can have beliefs, even true beliefs, about the objects that populate the visible world, there is no knowledge of such things (7.529b). It is not a defect in the philosopher-rulers so much as a defect in the world: they lack knowledge of the correct number because such things are by their very natures not knowable: one can have beliefs about particulars, but not knowledge. Even if the philosopher-queens and -kings get it right most of the time (which we can assume they will), they will miss the mark often enough to make a difference: they will join brides and grooms at the wrong time, the children will be neither good natured nor fortunate (8.546d). In short, non-gold children will be born to gold parents but, like lawlessness and other evils, this will go unnoticed (4.424d). The problem posed by these defective natures is exacerbated by their being nurtured badly, as the program of education that was laid out in such detail in Books II and III begins to go awry: they will have less consideration for music and poetry than they ought (8.546d). Thus the rulers will fail in their great duty, that they guard against the mixture of the metals in the souls of the next generation (3.415b). The rulers whose golden souls are infected with bronze and iron begin to see a gap between the citys good and their own. They question the prohibition on possessing private property, required by the citys foundational myth. They expect ruling to pay and so begin to drive a wedge into the ever-widening gap, hastening the aristocratic city toward the ruin prophesized at the end of Book III. The city is not unified literally, it has dis-integratedbeing no longer of one mind (8.545d) about who should rule and what is best for the city. As false rulers pull the city toward money-making, the true rulers and auxiliaries, whose souls are still pure gold and silver, pull in the other direction, towards virtue and the old order (8.547b). To end the strife, a deal is struck, settling on a middle way, between rational, aristocratic virtue and 232 Platos Republic: An Introduction appetitive, oligarchic wealth: timocracy, in which the good is honor and in which spirit rules the soul and the auxiliaries rule the city. The Timocratic City and Soul (8.547c550c) The timocratic city and soul do not exhibit justice. They cannot, as they are governed by the honor-loving spirited element, which is supposed to be reasons ally and helper (4.441a), not governor of soul and city. Only a soul and city in which each part performs its proper task can be just. Still, calling them unjust seems too strong. People for whom honor is the good will regard shame as badperhaps as the bad, the thing most to be avoidedand thus will avoid conventionally unjust conduct. This love of honor is fueled by their valu[ing] physical training more than music and poetry (8.548b), which also fuels a change for the worse in fundamental values. Justice, we know, is doing ones own work and not meddling with what is not ones own (4.433a), but in a timocracy those who do their work are called fools and held to be of little account, while those who meddle in other peoples affairs are honored and praised (8.550a). Thus justice begins to be regarded as the kind of simpleminded foolishness that Thrasymachus mocked in Book I. In accounting for the rise of the timocratic person, Socrates seems to give more evidence that he is not really a feminist, as he lays the blame for its rise at the feet of a carping, status-hungry wife who complains to her son about his fathers shortcomings. The aristocratic father, who is reminiscent of Book VIs shelter-seeker who wants to lead a quiet life and do [his] own work (6.496d), is not interested in ruling as his city degenerates, and this negatively affects his wifes status among the other wives. He is uninterested in money and does not fight back when he is insulted (8.549c). In short, his wife complains to their son that his father is unmanly [and] too easy-going (8.549d), since, presumably, he subscribes to Socrates proto-Stoic view that human affairs are not worth taking very seriously (10.604b) and thus is among those who are unwilling to occupy themselves in human affairs (7.517c). At his mothers urging, their son wants to be more of a man than his father (8.550a). It clear that Plato is criticizing a kind of masculinity that typifies and would be ascendant in an honor-driven, competitive culture. The timocratic son is not bad by nature, Socrates insists, but he The Decline and Fall of the Ideal City-Soul 233 is surrounded by people who value honor and victory more than virtue and truth, so it is no wonder, given how readily children absorb values from their culture, that he turns out as he does. Honor is a fine thing, as it can lead one to have a soul that is kalon, fine and noble and beautiful, and thus worthy of being honored. Kant thought it a facsimile of virtue, as it provides a nobler motive than selfinterest. Aristotle writes of a healthy competition in which people strive to emulate and even outdo each other in virtue.1 But honor as an internal good can easily give way to the external good of being honored, especially in a competitive, victory-loving culture. Being honored should be merely a foreseeable consequence of acting well, but it becomes instead the intended outcome, the goal aimed at. The Oligarchic City and Soul (8.550c555b) Changes to education and changes in value are again part of the story as timocracy degenerates into oligarchy. The most momentous change is wealths replacing honor as the over-arching goal of city and soul, as the competition for honor that drove the timocratic person finds a new object. It is no accident that Plato twice appeals to the notion of emulation in explaining this transition (the Greek term is (zlos), which is the root of the words zealous and jealous). Iron- and bronzesouled rulers see their fellows stretching and then disregarding the rules against private property; they emulate and compete with each other, which ultimately leads them to formally establish wealth as a qualification for ruling. Wealth is the criterion by which they choose the captain of the ship of state, refusing to entrust the ship to a poor person even if he was a better captain (8.551c). As wealthy craftspeople govern the oligarchic city, appetitein particular the desire to make money governs the soul. Thus appetite and the craftspeople operate in areas beyond their expertise, meddling in other peoples affairs (8.551e) the affairs of the guardians and auxiliaries. Platos psychology of the oligarchic person is subtle and fascinating. The oligarchic person subordinates reason to appetite, reducing reason to the merely instrumental role of determining the best means to the end 1 Aristotle, Nicomachean Ethics, IX.8 1169a610. 234 Platos Republic: An Introduction which appetite sets for himand thus embodies the Humean picture on which Reason is and ought only be the slave of the passions, and can never pretend to any other office but than to serve and obey them.2 This is not to say that Hume endorses the oligarchs substantive goal: he does not think our primary aim is or should be the pursuit of wealth. Humes point is structural, concerning the relation of reason and passion, not the substantive ends we pursue: passion, not reason, provides us with our goals and ends; reasons job is merely to determine the best means to achieve those ends. Although Plato regards wealth and virtue as polar opposites (8.550e), he implies that there is something about the desire for wealth that gives the oligarchs life order and discipline. The oligarch is unwilling to indulge what Socrates calls his dronish appetites (8.554c) for sensual gratification but instead is a thrifty worker, who satisfies only his necessary appetites (8.554a). Since reason does not govern his soul, he is not just, but he is not quite unjustat least his conduct is not reliably unjust. His baser appetites are kept in check, not by reason, as they are in the just, aristocratic soul, nor by a healthy sense of shame, as they are in the spirit-governed timocratic soul, but instead by fear. The oligarch fears that indulging his other appetites will be financially too costly. The contest between force and persuasion, raised in the opening scene of the Republic, is decisively settled in favor of force by the time oligarchy arrives. The oligarchs dronish appetites are forcibly held in check by his carefulness (8.554c) and thus his better desires are in control of his worse (8.554d). Carefulness is a fine quality; indeed, it is a trait the guardians must possess, given the importance of their task to the citys wellbeing (2.374e). Caution keeps the oligarchic person on the straight and narrow, more or less, but where they have ample opportunity to do justice with impunity (8.554c), they will probably take it. After all, what is needed for success in business, they will reason, is a reputation for justice: not being just but merely seeming just. Despite the oligarchs devotion to financial gain, Socrates insists that the true virtue of a single-minded and harmonious soul far escapes him (8.554e). This may seem an odd remark for Socrates to make, given the oligarchs focus on wealth, which certainly seems single-minded. But as is so often the case in the Republic, 2 Hume, Treatise, p. 415 (II.iii.3). The Decline and Fall of the Ideal City-Soul 235 the way things seem is not the way they are. I take Socrates point to be that while the oligarchs devotion to wealth is indeed single, it is not single-minded: it is not a product of rational reflection but rather of appetite. The tune his soul sings must be dissonant at times, since its parts are not playing their proper rolesreason should govern but here is subordinated to appetiteand the soul is ordered not by reason and persuasion but by force, and fear does not make for harmony. This lack of single-mindedness is also a feature of the timocratic city and soul, which, like the oligarchic city and soul, is in tension with itself. Toward the beginning of Book IV, Socrates worried about the corruptive and corrosive powers of wealth, fearing their slipping into the city unnoticed (4.421e). The changes all seem minor and inconsequential. What harm, for example, could allowing flutes and the Lydian mode do? But it is precisely their seeming innocuousness that makes changes to education and relaxing the Specialization Principle so dangerous. We can imagine the processes of rationalization at work as values such as justice and nobility are replaced by the drive for wealth. The oligarch is not someone who pays any attention to education (8.554b), at least not education in music and poetry! What a waste of time, we can imagine the oligarchs complaining. Educationespecially if it is publicly fundedshould be practical, teaching marketable skills to people regarded primarily as consumers and only secondarily if at all as citizens. If we listen closely, we can almost hear Dickens Mr Gradgrind weighing in: Teach these boys and girls nothing but Facts. Facts alone are wanted in life. Plant nothing else, and root out everything else.3 While the oligarch will perhaps embrace the pre-dialectic mathematical education spelled out in Book VII, they will re-purpose it in an antiSocratic way, insisting that number be studied by tradesmen and retailers, for the sake of buying and selling (7.525c), that its aim be practical, never theoretical. The careful and hard-working oligarch has a good reputation and is thought to be just (8.554c), but whatever his reputation, we know that his soul is not in fact just. He is the midpoint in the decay of the ideal city and soul. He is not good, but he is not thoroughly bad, either. He is someone like Cephalus, whom Socrates clearly respects. Cephalus is 3 Charles Dickens, Hard Times (London: Penguin Books, 1994), p. 10. 236 Platos Republic: An Introduction wealthy, and while he is fond of money, he is not too fond of it (1.330bc). He does not use his considerable wealth to indulge his sensuous appetites; instead, it has given him a moral cushion of sorts: because he is (and was born) wealthy, he is not tempted to act unjustly in in the pursuit of wealth. Cephalus has enough self-awareness to admit that his moral decency is not a consequence of unshakable inner virtue but owes a great deal to luck and external circumstance. The oligarchic city is really two cities, rich and poor, at war with each other, and it is relatively stable, but as its stability is born of fear and power rather than justice, it is not a stability that can last. And it does not last, Socrates thinks: it inevitably decays into democracy. The Democratic City and Soul (8.555b562a) Etymologically, democracy means rule (-cracy) of the demesthe people. Readers are often taken aback at the dim view Plato has of democracy, but it really should not be a surprise. Plato thinks that the majority cannot be philosophic (6.494a), so most people are incapable of possessing wisdom, knowledge of what is best for the city as a whole, which is the virtue required to govern well. I trust that we can understand why he takes this view, even if we disagree with him. The good in a democracy is freedom, which for Plato is not unambiguously good. He quickly associates it with license to do what [one] wants and to arrange [ones] own life in whatever manner pleases him (8.557b). License carries with it a hint of arrogance, and perhaps immaturity, reminiscent of the silly, adolescent idea of happiness (5.466b) condemned earlier. One way to think about Platos discomfort with this sort of freedom is that it is ungrounded in any rational principle and that it underwrites choices based on whim. The Specialization Principle has long since given way to the impulse of the moment. There is neither order nor necessity in his life (8.561d), Socrates says of the democratic person. He is unfocused, with the attention span of a golden retriever. Today he gives himself over to drinking and debauchery; next week he drinks only water and becomes an exercise addict; he tries business, he then dabbles in philosophy, etc. He lacks the discipline his oligarchic father had, and indeed his lifestyle is a reaction to parental frugality and austerity. The Decline and Fall of the Ideal City-Soul 237 Following the late Isaiah Berlin, philosophers often distinguish between positive and negative freedom. Freedom conceived negatively is the absence of constraint. The freedom of speech guaranteed in the First Amendment of the US Constitution, for example, is a guarantee against state interference with expressing ones views. But conceived positively, freedom is genuine autonomy and self-direction. As Berlin puts it, I wish my life and decisions to depend on myself, not on external forces [] I wish to be a subject, not an object; to be moved by reasons, by conscious purposes, which are my own, not by causes which affect me, as it were, from outside.4 The democratic persons freedom is largely negative; they are not prevented from doing as they like (subject, of course, to various reasonable constraints, e.g., that their conduct does not harm others). But the democrat seems too impulsive and reactive, too susceptible to external influences to count as positively free. They do not scrutinize their values or plans or adopt only those endorsed after a period of reflection, as the positively free person does. There is a deep sense in which the democrats reasons and purposes are not really their own. At the very least, they are ephemeral and shifting, and do not reflect the presence of a well-thought-out life-plan. So, we know what the democratic city and soul take the good to be. And in place of oligarchys wealth requirement, in the democratic city all citizensor, at least, all male citizenshave political rights: the city is ruled not by the wealthy craftspeople but by all the craftspeople. The political classes of the aristocratic city are a thing of the past, and the army comprises citizen-soldiers, rather than the professionals that Plato envisioned. But what governs the democratic soul? There are five kinds of constitutional arrangement, Socrates insists, but only three parts of the soulso by the time we arrive at democracy, we seem to have run out of parts. So what governs? 4 Isaiah Berlin, Two Concepts of Liberty, in Berlin, Liberty: Four Essays on Liberty, ed. by Henry Hardy (New York: Oxford University Press, 2002), https://doi.org/10.10 93/019924989x.001.0001, p. 178. 238 Platos Republic: An Introduction Interlude: Necessary versus Unnecessary Appetites Appetite governs the democratic soul, as it does in the oligarchic soul, but here Socrates makes a philosophically interesting distinction between kinds of appetites or desires. The democratic soul is governed by unnecessary desires, the sort the oligarch steadfastly and cautiously refused to indulge, while necessary desires govern the oligarchic soul. Socrates alluded to the distinction (without explaining it) when describing the oligarch, whom he called a thrifty worker who satisfies only his necessary appetites (8.554a). And indeed, the distinction between necessary and unnecessary desires is implicit in the difference between the rustic and the luxurious ideal cities. The latter comes about because the citizens have overstepped the limit of their necessities (2.373d), which suggests that in the rustic city, which Socrates regards as the true city [] the healthy one (2.372e), the citizens satisfy only their necessary appetites, whereas satisfying the unnecessary appetites fuels the luxurious city. So how do necessary and unnecessary desires differ? Plato gives a two-pronged definition of necessary desires: those we cannot desist from and those whose satisfaction benefits us [are] rightly called necessary for we are by nature compelled to satisfy them (8.558e). This and should be an or, however, since a desire that meets either criterion will count as necessary. Consider bread. As a basic element in the Greek diet, we can think of it as proxy for food generally. A desire for bread is necessary on both counts: first, we cannot desist from itwe cannot not want it, as a desire for food comes with our animal nature. Someone without this desiree.g., someone suffering from anorexia, which etymologically is the absence (the privative an-) of desire (orexis)would be very badly off and in an unnatural, unhealthy state. Second, satisfying a desire for bread is good for us, and indeed we enjoy it. While bread makes life possible, good bread makes life enjoyable. So, too, do the delicacies we put on the bread make life more enjoyable, but we can learn to do without them. Remember that it was the absence of delicacies that Glaucon decried in the first, rustic ideal city back in Book II (2.372c), claiming the city was fit only for pigs. So a desire for delicacies will also count as a necessary desire, since it is natural for us to desire something to put on the bread. Only an appetite The Decline and Fall of the Ideal City-Soul 239 that fails both counts will be unnecessary. Though Socrates does not say so, presumably this will vary from person to person: you may be able to enjoy a cocktail before and a glass or two of wine with dinner, but for an alcoholic, even a couple of drinks starts them on the road to selfdestructive drunkenness. So winealso a Greek stapleis necessary for some of us but unnecessary for others. Though the distinction between necessary and unnecessary desires is needed for Socrates to distinguish between the oligarchic and democratic souls, the democratic person rejects it, taking all desires to be equally worthy of pursuit: the democrat puts all his pleasures on an equal footing (8.561b). The democratic person does not deny the distinction in a conceptual way, holding it to be incoherent or nonexistent. Instead, they deny that the distinction is a suitable basis for action and choice, declar[ing] that all pleasures are equal and must be valued equally (8.561c). They do not think that necessary desires are better than unnecessary desires or that there is any reason to blush at pursuing what those frugal oligarchs regard as unnecessary [desires] that aim at frivolity and display (9.572c). Where their fathers pursued only necessary desires, the young democrats reject this frugal austerity (and thus the order and discipline their focus on necessary desires gave rise to) and seek to indulge the desires that characterize the neer-dowell drones. Although the democrat seems uninterested in thinking philosophically about Platos way of distinguishing necessary and unnecessary desires, we might find it worthwhile to do so, to see if there are independent reasons to reject it or at least to reformulate it, as it seems awkward to regard a desire for delicacies as necessary, since, as Socrates himself points out, we can learn to give them up. So we do not get too far afield, let us consider briefly the taxonomy of desires Epicurus (bce 341270) proposed. First, a word of warning: though the word epicurean has some resonance with ancient Epicureanism (which took pleasure alone to be good in itself, the view we identified in an earlier chapter as hedonism), Epicurus actually took the absence of pain and disturbance to be what pleasure truly is. For him, the pleasure that constitutes the good is not a full belly but a tranquil mind. Where Plato fuses necessary and natural desires, calling some desires necessary because they are natural, Epicurus distinguishes between 240 Platos Republic: An Introduction what is natural and what is necessary. For Epicurus, a necessary desire is one whose non-satisfaction causes physical pain. When we do not eat, we experience the pangs of hunger. Thus a desire for foodfor bread, as Socrates put itcounts as necessary. While every necessary desire is natural, for Epicurus, not all natural desires are necessary. The desire for bread is both natural and necessary. But desires for relishes, while natural, are not necessary. Think of a favorite dish. I love the Pha Ram Long Song at Ruam Mit Thai in downtown St Paul; its deliciousness makes my life better, but I can clearly live without it: it is a natural but unnecessary desire. If I show up only to find that the restaurant is no longer open on Sundays, I should react with mild disappointment: Oh, dang it! I was really looking forward to that. Oh well. I will ask my companions where we should go instead. If, on the other hand, I am not disappointed but really angry that the restaurant is closed and am still muttering I cannot fricking believe it! hours later, sulking and ruining dinner for everyone because I did not get what I wanted, then my desire is not only unnecessary, it is also unnatural. Excessive psychological distress at a desires not being satisfied is not natural: there is something wrong with me. So the difference between natural but unnecessary desires and unnatural and unnecessary desires is not a difference in objects desired but rather in the desirer themself. I should be able to eliminate my desire for x when x is difficult to obtainor if x is bad for me. Epicurus thinks that the source is usually a groundless opinionsome false belief that I cannot be happy unless I have this particular Thai dish or that flavor of ice cream or that I get a promotion, etc. In fact, for Epicurus eliminating such desires is one of the keys to happiness. No gourmand himself, Epicurus thought that Plain fare gives as much pleasure as a costly diet, when once the pain of want has been removed, while bread and water confer the highest possible pleasure when they are brought to hungry lips. To habituate oneself, therefore, to simple and inexpensive diet supplies all that is needful for health, and enables a man to meet the necessary requirements of life without shrinking, and it places us in a better condition when we approach at intervals a costly fare and renders us fearless of fortune.5 5 Epicurus, Letter to Menoeceus, in The Art of Happiness, ed. by George Strodach (New York: Penguin Books, 2012), p. 159 [DL 10.13031]. The Decline and Fall of the Ideal City-Soul 241 Epicurus taxonomy of desire seems an improvement on Platos largely because he separates naturalness and necessity, which Plato conflates. Platos way of distinguishing necessary and unnecessary seems awkward and even mistakenbut if so, it is not a fatal mistake but rather one that is easily repairable. Democracy, Continued Equality comes a close second to freedom as democracys defining good. Not only are all pleasures and desires equal, but so too are men and women (8.563b) (which is yet another point against the view that Socrates is a feminist, given the disdain he has for democracy), slave and owner, citizen and non-citizen (8.562e), and even humans and nonhuman animals (8.563c). Where the oligarchic father satisfies only his necessary appetites [] and enslaves his other desires as vain (8.554a), his democratic son celebrates the liberation and release of useless and unnecessary pleasures (8.561a). Plato stresses how attractive the democratic polity appears: it is multicolored (8.559d, 561e) and embroidered with every kind of character type (8.557c). But it is a specious beauty. The democratic children of oligarchic parents seem to suffer from what is sometimes called affluenza: they are fond of luxury, incapable of effort either mental or physical, too soft to stand up to pleasures or pains, and idle besides (8.556b). Their teachers, perhaps afraid of low scores on student surveys, fear and flatter them (8.563a), and their parents want most of all to be their friends. It is a prescription for disaster, Plato thinks. Despite its obvious shortcomings, taking the good to be wealth has its benefits, because it is a value with content and moreover one that imposes discipline and order. Freedom, on the other hand, is formal rather than contentful, and indeed it is perhaps too formal and too opentextured to guide ones life. Aristotle wrote that not to have ones life organized in view of some end is a mark of much folly.6 Plato surely agrees; he seems to be arguing that freedom is ill suited to play the role the democrat has cast it in. Do whatever you want is, technically, a lifeguiding principle, but so long as there are few or no restrictions on what 6 Aristotle, Eudemian Ethics, I.2 1214b10. 242 Platos Republic: An Introduction one should want or desire, it is going to lead to chaos. So what we have is not so much democracy as anarchy (anarchia): the absence of a leader or leading principle (8.562e). We see this most clearly in the way the correct, aristocratic scheme of values is turned on its head in the democratic city and soul. Reverence, the proper sense of respect and shame that proper stories about the gods were meant to cultivate, is thought of as foolishness. The cardinal virtue of moderation is regarded as the cardinal vice of cowardice, and the vice of shamelessness is now become courage. Insolenceliterally, (hubris)is regarded as good breeding and anarchy is freedom. They mistake prodigality or wastefulness as the public-spirited virtue of magnificence (private spending for public goods such as producing a tragedy, outfitting a trireme, etc.). Where the oligarchic father was not willing to spend on such matters, the democratic son goes wrong in the other direction, spending wildly. It is an upside-down world, but of course the democratic person thinks it is the best of all worlds, free of stuffy conventions and old-fashioned thinking. The Tyrannical City and Soul (8.562a9.576b) Platos explanation of the transformation from democracy to oligarchy has the elegance of Newtons third law of motion, which states that for every action, there is an equal and opposite reaction. For Plato, excessive action in one direction usually sets up a reaction in the opposite direction (8.563e), so the extreme freedom found in democracies leads inexorably to the total lack of freedom found in tyrannies. Plato thinks his proto-Newtonian principle is not merely politicalit explains changes in seasons, plants, and bodies, toobut alas we do not have space to pursue this fascinating line of thought. It is no accident that Plato appeals to a principle of physics here. Nor should it be a surprise; after all, it is something like entropy that explains why the ideal state begins to decay in the first place. In addition to physical explanations of political events and changesand it is helpful to keep in mind that our word physics derives from the ancient Greek word [phusis], which means nature more broadly he also appeals to economic factors. Consider first the change from oligarchy to democracy. Having exploited existing sources of wealth, The Decline and Fall of the Ideal City-Soul 243 the oligarchs need new sources, new markets, so they hit upon one with great contemporary relevance: they find young people to be a potentially lucrative market to lend money to. More interested in profit than people, they are unwilling to enact laws to prevent young people who have had no discipline from spending and wasting their wealth, so that by making loans to them, secured by the young peoples property, and then calling those loans in, they themselves become ever richer and more honored (8.555c). Although the details differ, something similar is afoot in the US, where student loan debt now tops one trillion dollars, exceeding even credit card debt. Though the cause is massive state disinvestment in higher education rather than predatory lending, the results seem the same: indebted young people. While indebtedness in the US seems to push us away from democracy and toward oligarchy, in Platos world things go in the opposite direction: as the rich become fewer but richer and the poor become poorer but grow in number, an actual and not merely metaphorical civil war breaks out and the people are victorious. In true Thrasymachan fashion, the holders of political power pass laws that benefit themselves rather than the citizenry at large or the state as a whole. They resist suggestions that the majority of voluntary contracts be entered into at the lenders own risk (8.556b), much as contemporary bankers resist calls to eliminate the moral hazards of a system that privatizes profit but socializes loss by having the citizenry bail out the too big to fail banks and investment firms that crashed the world economy in 2008. The transition to tyranny is fueled by the would-be tyrants making all sorts of promises both in public and private, freeing the people from debt [and] redistributing the land to them (8.566e). Thus economic factors are at work here, as well. Many readers will note eerie similarities with todays global political climate, which seems to feature the emergence of the strongman whom the people have set up as their special champion (8.565c). I will leave it to more economically and politically sophisticated readers to pursue this for themselves; there is plenty of food for thought here, whereas elsewherethe Republic is surprisingly contemporarily relevant. 244 Platos Republic: An Introduction Interlude: Lawless versus Lawful Desires Earlier it seemed that Socrates had run out of parts of the soul, there being five kinds of souls (and cities) but only three parts in the soul. To distinguish oligarch and democrat he distinguished between necessary and unnecessary desires. Here a similar problem arises: what governs the tyrannical soul? And so, at the beginning of Book IX Socrates makes a distinction between kinds of unnecessary desires: some are lawless, and some are law-abiding or at least law-amenable. In an account that rings some Freudian bells, Plato indicates that the lawless, unnecessary appetites are most apparent in our dreams, for it is there that our beastly and savage part (8.571c) emergesas anyone who has had not just a weird but a genuinely creepy dream can attest. There is nothing that is off-limits for the lawless, unnecessary desires; in their grip a person does not shrink from trying to have sex with a mother [] or with anyone else at all, whether man, god, or beast. It will commit any foul murder, and there is no food it refuses to eat (9.572d). Whom one has sex with, whom one kills, and what one eats form an unholy trinity indeed. The role played here and elsewhere in the Republic is intriguing; it was pivotal in the rejection of the first ideal city and in understanding the lawless unnecessary desires which define the tyrant. (It may be helpful to note that the Greek word translated as lawless is [paranomos], which connotes not the absence of law so much as going beyond it.) It is not that only the tyrant has lawless unnecessary appetites; they are present in almost everyone, Plato thinks, but they govern the tyrannical soul. In most of us they are kept at bay by constraints internal (reason, in the best of us; shame or fear, in the rest of us) or external (the law). Indeed, Platos account of psychic and political degeneration is an account of how these constraints change. In the aristocratic, philosophical soul, it is reasonrational persuasion that keeps the beastly desires at bay. They are tamed by arguments (8.554d) and by the meditative practice Plato counsels undertaking before one goes to bed at night (9.571e2a). The spirit-governed timocrat, more responsive to honor than to reason, is motivated by a healthy sense of shame, honors opposite. Remember that much of the point of musical-poetic education is cultivating the right The Decline and Fall of the Ideal City-Soul 245 distastes (3.401e)of being properly disgusted. The timocrat should be disgusted at the thought of ignoble or dishonorable thoughts and deeds and presumably would not even be tempted to embezzle from or cheat a widow or orphan, though the oligarch probably is. For the oligarchs dronish, unnecessary desires are not held in check by reason or shame but rather by fear; and if the oligarch believes they can do injustice with impunity (8.554c), they probably will, just as Gyges did back in Book II (2.360c). The democratic person wavers between fear and shame, being too unsettled to have a constant, characteristic motivation: sometimes their disordered soul is ordered by a kind of shame (8.560a), which overcomes some of their base appetites and expels others. But at other times they feel neither shame nor fear in front of [their] parents (8.562e), thinking themself their parents equal and taking shamelessness to be a form of courage (8.560e). The tyrannical soul is free of all control by shame or reason (9.571c). As the tyrannical city long ago abandoned proper education in music and poetry, the main bulwark against lawlessness (4.424d), this should come as no surprise. Tyranny, Continued Although Plato is less explicit about the tyrannical souls good than he is with the defining goods of the timocratic, oligarchic, and democratic souls, it seems that the tyrants good is erotic love and desire: [ers]. But this is not really erotic love, as opposed to familial or friendly love. It is mad, addictive, erotic desire for everything. Plato told us back in Book III that the right kind of erotic love : the orthos ers is the love of order and beauty that has been moderated by education in music and poetry [ which] has nothing mad or licentious about it (3.403a). The tyrants erotic love, by contrast, is a kind of madness ( [mania]) (9.573b) that leads not merely to house-breaking, purse-snatching, temple-robbing and the like (9.575b), a cluster of unjust acts that pop up elsewhere in the Republic (1.344a, 4.443a, 8.552d), but to complete anarchy and lawlessness (9.575a). It is outdoingpleonxiagone mad. Thus the tyrant when awake is what most of us are when we sleep and have dark dreams of fulfilling lawless unnecessary desires (9.574e). 246 Platos Republic: An Introduction The tyrant is the inversion of the philosopher, who, in contrast to lovers of opinion and the cave-dwellers, is awake (5.476d, 7.520c). The tyrants waking life is like the nightmare we described earlier (9.576b). Their desires are not merely many but are insatiable, for they are like a vessel full of holes (9.586b): no sooner has one appetite or lust been satisfied than another makes its demands. Always wanting more, nothing is ever enough. Epicurus seems to have diagnosed him exactly: Nothing is enough for the man for whom enough is too little.7 The portrait of the tyrant is interesting, but some readers may feel that it misses the mark. It does not seem to fit tyrants most of us are familiar withfor example, Hitler and Stalin, neither of whom seemed to be a bubbling cauldron of lust, unable to control himself. Plato seems to have captured the essence of an addict running wild, manic and disordered and undisciplined. But he seems not to have captured the cold, calculating tyrant that Thrasymachus praises. The tyrant, after all, is supposed to be like a wolf (8.566a), preying upon the flock that the guardian-shepherds try to protect with the help of the sheepdog-auxiliaries, to bring the metaphor full circle. While the wolf as portrayed by Plato poses a threat to the flock, it is hard to see how this undisciplined, manic, deeply disturbed person can appear a paragon of justice, as the argument of the Republic requires. Someone more ordered and calculating seems needed, someone possessing the oligarchs singular focus and discipline, someone whose soul is as ordered and reason-governed as the just personsbut someone who possesses cleverness rather than wisdom: that is, someone who knows what best serves their interests rather than the citys. In short, the tyrant should be a wise villain (3.409c). No doubt there are people with dark secret lives who manage to convey an ordered, mild faade. But it is difficult to imagine how someone whose inner life is as deranged and insane as Platos tyrant is could manage to appear completely respectable. Readers might wish that Adeimantus would push back here, as he has done elsewhere in the Republic. It is a shame that Adeimantus does not resist Glaucons taking over the argument (9.576b) at the conclusion of the account of the tyrant and raise some of these objections to Socrates. Because 7 Epicurus, Vatican Sayings #68, in The Art of Happiness, p. 183. The Decline and Fall of the Ideal City-Soul 247 he does not, we will want to keep them in mind as we look at the arguments that the just life is happier than the unjust life, to which we now turn. Some Suggestions for Further Reading Readers interested in the philosophical thought of Epicurus will find his extant writings along with a helpful introductory essay in The Art of Happiness, trans. by George Strodach (New York: Penguin Classics, 2012). Epicurus thought is expressed vividly in one of the great poems of world literature, Lucretius, The Nature of Things, trans. by Alicia Stallings (New York: Penguin Books, 2007). The story of the fifteenthcentury rediscovery of it is the subject of Stephen Greenblatt, The Swerve: How the World Became Modern (New York: W.W. Norton & Company, 2012), which won both the Pulitzer Prize and the National Book Award. In presenting Epicurus taxonomy of desire, I draw on an excellent essay, Raphael Woolf, Pleasure and Desire, in The Cambridge Companion to Epicureanism, ed. by James Warren (New York: Cambridge University Press, 2009), https://doi.org/10.1017/ccol9780521873475, pp. 15878. Readers interested in an accessible, erudite discussion of the decay of the city and soul will profit from G.R.F. Ferrari, City and Soul in Platos Republic (Chicago: University of Chicago Press, 2005). As many readers will have noticed for themselves, there has been a revival of popular interest in Platos conception of tyranny in light of recent electoral events in America. There are many interesting opinion pieces online. For a scholarly take, interested readers might see the essays collected in Trump and Political Philosophy: Patriotism, Cosmopolitanism, and Civic Virtue, ed. by Marc Benjamin Sable and Angel Jaramillo Torres (London: Palgrave Macmillan, 2018), https:// doi.org/10.1007/9783-319744278, or in Trump and Political Philosophy: Leadership, Statesmanship, and Tyranny, ed. by Angel Jaramillo Torres and Marc Benjamin Sable (London: Palgrave Macmillan, 2018), https://doi. org/10.1007/9783-319744452. Readers interested in a brief, wise, and oddly hopeful look at tyranny from one of the worlds leading historians of modern Europe will 248 Platos Republic: An Introduction certainly want to read Timothy Snyder, On Tyranny: Twenty Lessons from the Twentieth Century (New York: Tim Duggan Books, 2017). Unidentified artist, Image satirique du tennis chez les Anciens, La revue athltique, 3 (1890), 169. Photograph by Skblzz1 (2018), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/File:Image_ satirique_du_tennis_chez_les_Anciens_(1890).jpg 13. The Republics Second Question Answered: Three and a Half Arguments that the Just Life is Happier, Book IX At long last, in Book IX Socrates is ready to address the Republics second question, Is a just life happier than an unjust life? There is a lot at stake here, as the argument concerns no ordinary topic but the way we ought to live (1.352d). It is important to bear in mind that the ought here is not necessarily a moral ought. Indeed, it seems trivially true that one morally ought to live a morally good life. Socrates is asking a question that does not presuppose a moral answer.1 He is asking what is the best sort of life for a human being: is it a life of acting justly, or am I personally better off acting unjustly when it pays to do so, all things considered? If I cannot be happy without being just, then I have a good, self-regarding reason to live justly. Socrates initially thought that he had answered this question with Book Is Function Argument, but he quickly realized that he jumped the gun in concluding that the just life is happier before determining what justice itself is. But now, having determined what 1 This is a point driven home forcefully in the opening chapter (Socrates Question) of Bernard Williams, Ethics and the Limits of Philosophy (Cambridge, MA: Harvard University Press, 1986), esp. pp. 56. Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.13 252 Platos Republic: An Introduction justice is to the satisfaction of Glaucon and Adeimantus and the rest, Socrates is ready to deliver. Argument #1: Comparing Characters (9.576b580c) It is clear to everyone, Socrates says, that there is no city more wretched than one ruled by a tyrant and none more happy than one ruled by kings (9.576e). So much for political happiness. As for personal happiness, settling the question requires us to compare the just and unjust livesthe lives of the aristocratic philosopher and the tyrant, respectively. Actually, it does not require us to do this; it requires someone who is competent to judge (9.577a) to do so. Their verdict will decide the case. So, who is fit to judge? (9.576e) The person, Socrates answers, who in thought can go down into a persons character and examine it thoroughly, someone who does not judge from outside (9.577a). After my making so much of the enlightened philosophers going down into the Cave, readers might be deflated at learning that a different verb, [enduein] is being translated go down. Its primary meaning is to try on, as clothes; it can also mean to go into. Though it lacks literary razzle-dazzle, the crucial point is that this is something that the fit judge can do in thought: they need not actually (i.e., in body) become a drug addict to assess the addicts life, for example; they can understand this life without having lived it because a philosopher grasps the relevant Form and its relation to the Form of the good. This squares with Socrates earlier observation that a good judge is aware of injustice not as something at home in his own soul, but as something present in others [ he] recognize[s] injustice as bad by nature, not from his own experience of it, but through knowledge (3.409b). Another crucial point, related to the first, is that the fit judge does not judge from the outside; they are not dazzled by the faade that tyrants adopt [] but [are] able to see through that sort of thing (9.577a). This echoes and indeed answers Adeimantus earlier complaint that the way justice is praised in Athenian culture leads young people to cynically conclude that they should create a faade of illusory virtue around [them] to deceive those who come near (2.365c). The Greek being translated a faade of illusory virtue ( [skiagraphian artes]) should remind us of the shadow-filled world of the Cave, as The Republics Second Question Answered 253 it literally means a shadow-painting of virtue. What the competent judge finds is that the tyrannical soul is full of disorder and regret and indeed is least likely to do what it wants (9.577e). The tyrannical soul lacks self-control (9.579c) and its desires are not merely unsustainable but are unfulfillable: the tyrannical addict always wants more. One especially striking feature is the tyrants friendlessness: someone with a tyrannical nature lives his whole life without being friends with anyone, always a master to one man or a slave to another and never getting a taste of either freedom or true friendship (9.576a). For most readers, friendship is an important component of a happy life, and Plato would agree. His student Aristotle regarded friendship as one of lifes greatest goods, one we cannot lack and still flourish. It seems a generalbut not exceptionlesstruth that friendship is necessary for happiness. It is not too difficult to see why the tyrant is incapable of friendship. First, friendship is typically a relationship between equals, which the contemporary philosopher Laurence Thomas takes to mean that neither party is under the authority of the other or entitled to the deference of the other.2 One friend might be wiser and the other might frequently heed their advice, but the other friend is not obligated to do so: a friend can make suggestions but not issue commands. This is one reason that workplace friendships can be problematic: there may come a time when my friend has to switch roles, from friend to boss, which puts us in a relationship of inequalityand to that extent, at that moment, our friendship recedes into the background. I thought you were my friend, I pout. I am, she replies. But I am also your supervisor, and you need to clean up that spill in aisle six right now or were going to have a real problem. The tyrannical soul is bent on outdoing everyone; life is a constant competition in which one dominates or is dominated, and that does not leave much room for friendship, as the tyrant cannot abide anyone being their equal, let alone their superior. A second reason that friendship is unavailable to the tyrant is that friendship requiresand indeed is a kind oflove. Even if we think Platos conception of love is overly cognitive and insufficiently affective, we can agree with him that love involves a commitment to the others 2 Laurence Thomas, Friendship and Other Loves, Synthese, 72.2 (1987), 21736 (pp. 217, 22123). 254 Platos Republic: An Introduction wellbeing, for the others own sake. This seems like an impossibility for the tyrant, who always seeks to further their own interests and sees others merely as a means to their own ends. The tyrant might cultivate what seem to be friendships, but insofar as they seek their own and not their would-be friends wellbeing, they are cultivating an ally, not a friend. So when it is in the tyrants interest to turn on the allyor the allys interest to turn on the tyrantthey will do just that. It is no accident that The Godfather, Part Two ends with Michael Corleone alone and brooding, isolated and friendless. Argument #2: The Souls Distinct Pleasures (9.580d583a) The second argument subtly shifts the terms of the argument from happiness to pleasure. Despite Socrates earlier rejection of hedonism, there is nothing problematic about the shift to talk of pleasure here. Indeed, it makes perfect sense for Socrates to do so, given that he is trying to show that everyone has good reasons to live justly rather than unjustly. Thus it makes sense to focus on happiness in terms of pleasure, since how pleasant or enjoyable a life is takes up the individuals own perspective, as the argument requires. Each of the souls three parts has its own distinctive pleasure, so the question becomes which parts pleasures are most pleasantthe pleasures of the rational part or the spirited part or the appetitive part? In other words, is the just life, in which reason governs, more first-personally pleasant than the life in which appetite rules? There is a wrinkle in Socrates approach here: he insists that there are three primary kinds of people: philosophic, victory-loving, and profit-loving (9.581c). Offering three possibilities may be an improvement upon thinking that there are two kinds of people in this world, but even here readers may rightly object that this division is far from exhaustive, as it omits people who are peace-loving or family-loving. Indeed, Socrates himself earlier suggested another option toward the end of Book V: lovers of beautiful things. Such people (and many others) do not seem to fit any of Socrates three types, so we might rightly resist Socrates attempt at shoehorning here. But the wrinkle becomes difficult to iron out if we recall that Socrates has just finished a detailed account of five The Republics Second Question Answered 255 kinds of people. His distinction between three kinds of people accounts for the aristocratic, timocratic, and oligarchic souls, but what about the democratic and tyrannical? It is puzzling, especially since he is supposed to show that the really just but apparently unjust person is happier than the really unjust but apparently just person, which requires that he compare the aristocrat and the tyrant. Socrates might respond that the third, appetitive kind of life includes the democrat and tyrant as well as the oligarch, but given the way the oligarchs desire for wealth tempered their other desires and bestowed order in their soul, this seems less than satisfactory. This might be a significant problem if this were the only argument given by Socrates that the just life is happier, but as the argument that will follow is the greatest and most decisive (9.583b), all is not lost. Still, though, this is another place where the reader might wish Glaucon or Adeimantus or someone might notice the issue and speak up. Now, if we ask each representative of the kinds of life which is the happiest, each will insist that their own is. We have no reason to doubt the sincerity of their testimony: each believes their life is more pleasant than the others. It is crucial here to appreciate Socrates caveat: the dispute is not about which way of living is finer or more shameful or better or worse, but about which is more pleasant and less painful (9.581e). That is, the dispute is not a moral or normative one: the philosopher is not arguing that while the money-lovers life is more pleasant the philosophers own pleasures are better, higher quality pleasures (as John Stuart Mill suggests in Utilitarianism); the philosopher asserts the descriptive, quantitative claim that the pleasures of reason are more pleasant than those of spirit or appetite. A relativist or subjectivist will suggest that the dispute cannot be settled, shrugging and rhetorically asking, Whos to say? Socrates, though, does not think that the relativists question is rhetorical and offers an answer: the competent judge is to say. While it is true that each of the three offers testimony that their life is most pleasant, only the philosopher offers expert testimony, so to speak, since only the philosopher is really competent to judge the issue. Judging competently and indeed judging well is a matter of experience, reason, and argument (9.582a), Socrates tells us. The philosopher clearly has the advantage as regards reason, since reason governs their 256 Platos Republic: An Introduction soul. And they clearly have the edge as regards argument: argument is the instrument by which we judge, and argument is a philosophers instrument most of all (9.582d). As for experience, Socrates argues that the philosopher alone has experienced all three kinds of pleasure: the philosopher has enjoyed the pleasures that come with having ones desires and appetites satisfied and with being honored, but neither the honor-lover nor the appetitive money-lover has any experience of the pleasure of knowing the Forms. Thus, Socrates argues, since the philosopher alone is a competent judge, we should accept their verdict: the philosophical, aristocratic life, which is the just life, is the happiest of the three. Many readers will be less confident about this than Socrates seems to be. First, some will doubt that grasping the Forms exhausts the possibilities for intellectual pleasure. It is not as though investment bankers and plumbers do not find their work intellectually challenging and rewarding. While they no doubt enjoy being well compensated, many also enjoy the challenges of putting together complex financial instruments and solving construction problems. Although one would hope that intellectual snobbery is not at work here, one might well fear that it is, leading Plato to downgrade not only the manual arts but also intellectual arts not aimed at abstract knowing. A second concern focuses on that claim that the philosopher has experienced the pleasure of being honored and thus is a better judge than the honor-lover. This is difficult to square with the attitudes towards philosophy that Socrates dealt with in Book VI, where he conceded that people who think that philosophers are vicious or useless seem [] to speak the truth (6.487d). It turned out, of course, that the public mistakenly takes sophists to be philosophers and thus that the slander [against] philosophy is unjust (6.497a). But even so, in the very act of defending philosophy against this slander Socrates gives evidence that slander is afoot and thus that philosophers know very little of being honored. Remember that Glaucon imagined the idea of philosopherkings would be met not with relief but with people snatch[ing] any available weapon, and mak[ing] a determined rush at you, ready to do terrible things (5.474a), so it is not difficult to doubt Socrates claim that philosophers are well acquainted with being honored. Nor does his claim that honor comes to each of them, provided that he accomplishes his The Republics Second Question Answered 257 aim (9.582c) encourage confidence. In the last chapter we discussed the difference between the external good of being honored and the internal good of being honorable or worthy of honor. Indeed, in defending philosophy against slander, Socrates argues that philosophersthe genuine philosophers he tries to distinguish from the frauds in Books V, VI, and VIIare honorable, but he does not (and seemingly cannot) show that they have in fact been honored. He needs to establish the latter, descriptive claim that philosophers are actually regarded, not the former, normative claim about what sort of treatment they deserve or are entitled to. So there is reason to doubt the cogency of the second argument. As usual, we might agree with its conclusionthat the just life is happier and preferablebut regard this argument as failing to justify it. That is the bad news. The good news is that, as noted above, Socrates regards the next argument as the greatest and most decisive (9.583b) of the three. Let us see what it has to offer. Argument #3: The Metaphysics of Pleasure (9.583b588a) The third argument, which I call the Metaphysics of Pleasure Argument, is the philosophically most interesting of the three, arguing that the pleasures of reason are more pleasant than the pleasures of spirit or appetite because they are more real; the latter seem the result of shadow-painting ( [eskiagraphmen]) (9.583b) by comparison, the sorts of things we expect to encounter on the wall of the Cave. It is also the philosophically most precarious, since it presumes the reality of the Platonic Forms. I will go a little out of order in presenting the argument and make the existential sense of the verb to be more apparent. Here is the heart of the argument, as Socrates makes it (with a little help from Glaucon): And isnt that which is more [real], and is filled with things that are more [real], really more filled than that which is less [real], and is filled with things that are less [real]? Of course. 258 Platos Republic: An Introduction Therefore, if being filled with what is appropriate to our nature is pleasure, that which is more filled with things that are more [real] enjoys more really and truly a more true pleasure, while that which partakes of things that are less [real] is less truly and surely filled and partakes of a less trustworthy and less true pleasure. That is absolutely inevitable. (9.585d-e) At the heart of the argument is an understanding of pleasure as the result of being appropriately filled. Think of the pleasure a good, simple meal affords when you are hungry, or the pleasure of enjoyingi.e., being filled withgood music. Too much filling, be it too much food or music that is too loud, does not yield pleasure, since pleasure requires appropriate filling. Since what is more real is more filling and what is more filling is more pleasant, it follows that what is more real is more pleasant. But since the Forms are more real than any particulars, they are more filling, and thus the pleasure of knowing the Formswhich is the distinctive pleasure of the reasongoverned, just personis greater than the pleasures of being honored or having ones appetites satisfied. Stated in premise-conclusion form, the argument looks like this: P1 What is more real is more filling. P2 What is more filling is more pleasant. P3 The objects of the rational pleasures are more real than the objects of the spirited pleasures and the appetitive pleasures. C1 Therefore, rational pleasures are more filling than spirited and appetitive pleasures. (From P1, P3) C2 Therefore, rational pleasures are more pleasant than spirited and appetitive pleasures. (From P2, C1) P4 Each kind of life has a distinctive pleasure, determined by which part of the soul rules: the just persons pleasures are rational pleasures; the unjust persons pleasures are appetitive pleasures. C3 Therefore, the just life is more pleasant than the unjust life. (From C2, P4) C4 Therefore, the just life is happier than the unjust life. (From C3) The Republics Second Question Answered 259 As with the previous argument, it is important to bear in mind Socrates caveat that the argument concerns quantity, not quality: it is not an argument about which way of living is finer [] or better [] but about which is more pleasant (9.581e). The argument concerns which life contains the most pleasure, not a ranking of the pleasures in terms of quality, where, for example, intellectual pleasures are superior to appetitive pleasures. It would not be unreasonable for Socrates to insist that the just persons pleasures, being pleasures of the best part of the soul, are better, higher quality pleasures, but to concede that rational pleasures are not as pleasant as appetitive pleasures. But Socrates does not make this argument. Instead, he argues that rational pleasures are more pleasant than appetitive pleasures. So the Metaphysics of Pleasure Argument implies that the pleasures of doing philosophy or solving a calculus problem are more pleasant than the pleasure of sex. And that is going to strike many readers as preposterous. I think Plato is fully aware of how preposterous this seems, and he has a response ready. This response actually comes before the argument as I have stated it, hence the going out of order I mentioned above. Platos response is that while it seems that appetitive pleasures are more pleasant than rational pleasures, this is an illusion and not how things really are. Contrary versus Contradictory Opposites This is the point, I think, of the analogy he draws between pleasure and space. There is an up, a down, and a middle in space (Plato seems to be thinking of space as place, as a large container or room). If I am down and start ascending, I might mistakenly think I am at up when in fact I am merely at middle. Someone who is at up and then descends might think they are at down when they are at middle. If we meet, we might disagree about where we are, neither of us realizing that we at middle. Just as there is an up, a down, and a middle in space, Socrates suggests that there is pleasure, pain, and a neutral state of calm. And we regularly, wrongly take up/down and pleasure/pain to be contradictory opposites when in fact they are contrary opposites. A pair of opposites is contradictory when at least and at most one of them must be true or apply in a given situation; a pair is contrary when 260 Platos Republic: An Introduction at most one must be true, but it might be that neither is true or applies. Consider hot and cold. They are clearly opposites, but they are contrary opposites: while at most one of them applies to a given object, it may be that neither does. The place where you are reading this book might be hot or it might be cold, but it might be neither: it might be cool, warm, tepid, chilly, balmyeven room temperature. (Here we should remember the Opposition Principle from Book IV: if both of a pair of opposites applies, this suggests that the thing they apply to has parts. If I am both hot and cold, part of me is hot and part is cold, or I am hot now and then cold in an instant, etc.) While hot and cold are contrary opposites, cold and not-cold are contradictory opposites: everything is either cold or not-cold. Tucson in July? Not cold. Eau Claire in January? Cold. The number twelve? Not cold: numbers have no temperature, so they go in the not-cold column. On a well-written true-false question, true and false are contradictory opposites: at least and at most one of them is correct. But, other things being equal, true and false are contrary opposites: many things are neither true nor false. Questions are neither true nor false (although the answers to them might be true or false); exclamations (dang!) are neither true nor false; and of course non-linguistic itemspicnic tables, peanut butter, pencils, etc.are neither true nor false, since they make no assertions (though of course they can be what assertions are about). Many of us make mistakes when it comes to opposites. We think that helping and harming are contradictory opposites when in fact they are contrary: action can make a thing better off (helping) or worse off (harming) or leave it neutral. The good-hearted but dim-witted Ricky Bobby of Talladega Nights lives his life mistakenly thinking that first and last are contradictory opposites: If you aint first, youre last! he insists.3 With the help of his father (his confusions source), Ricky later comes to see the folly of this wisdom. Platos suggestion, I think, is that most of us take pleasure and pain to be contradictory opposites when in fact they are contraries. After a week in bed with the flu, the first day of feeling normal again seems pleasant, but it is really only not painful: I am mistaking the neutral state of calm for pleasure. After an exhilarating, inspiring vacation a return to normal is a real downer, but 3 Talladega Nights: The Ballad of Ricky Bobby, dir. by Adam McKay (Sony Pictures, 2006). The Republics Second Question Answered 261 I am probably just mistaking the neutral state of calm for pain, having been experiencing so much pleasure. Optical and Hedonic Illusions A person who is inexperienced in what is really and truly up, down, and in the middle (9.584e) will regularly make mistakes about where they are since they will mistake up and down to be contradictory opposites. And similarly, those who are inexperienced in the truth [and] have unsound opinions (9.584e) will regularly make mistakes about what they are experiencing. Heres the catch: becoming experienced in the truth and having sound opinions will not ensure that we are no longer subject to illusions about where we are or what we are feeling: it still feels like I am at up when I am only at middle, and this still feels like pleasure when in fact it is only non-pain. But being experienced in the truth and having sound opinions I can now know that things are not as they appear to me. Consider the famous Mller-Lyer illusion, below in Fig. 4: Fig. 4. Mller-Lyer illusion. Photograph by Fibonacci (2007), Wikimedia, CC BY-SA 3.0, https://commons.wikimedia.org/w/index. php?curid=1792612) It seems to be psychologically impossible to see the line segments as the same length: try as we might, the lower one just looks longer. If we measure the lines, as in Fig. 5, we can see that they are the same length: 262 Platos Republic: An Introduction Fig. 5. Mller-Lyer illusion. Photograph by Fibonacci (2007), Wikimedia, CC BY-SA 3.0, https://commons.wikimedia.org/w/index. php?curid=1792612) Even so, when I look back at Fig. 4, I cannot see them as being the same lengthI assume readers have the same experience. Our senses deceive us: what seems to be the case is not what is the case: This deception is persistent and not correctable by reasoning and measurement in that we see the lines as having different lengths even when we know that they are the same length. That is what makes it an optical illusion. The philosopher Jessica Moss argues that Plato is suggesting that just as we are prone to optical illusions, we are also prey to hedonic illusions: illusions about pleasure.4 Of course sexual pleasure seems more pleasant than rational pleasure, just as the bottom line seems longer than the top line: there is no way to perceive the comparative lengths of the lines accurately, just as there is no way to perceive the comparative amounts of the pleasures accurately. Measuring the lines tells us that our visual perception tricks us, just as rational argument tells us that our hedonic perception tricks us. Calculating, measuring, and weighting are the work of the rational part of the soul (10.602d), Socrates will tell us in Book X. And of course, argument is a philosophers instrument most of all (9.582d), since it is the rational instrument par excellence. Reason cannot alter our visual experience of the lines, making us see them as having the same lengthbut it can remind us that our perception is faulty and that they are in fact the same length. And similarly, reason cannot make us experience rational pleasures as more pleasant than appetitive pleasures, it can tell us that they are. Reason cannot make us experientially immune to optical or hedonic illusions: we will continue to experience them. But it can render us rationally immune to them: 4 Jessica Moss, Pleasure and Illusion in Plato, Philosophy and Phenomenological Research, 72 (2006), 50335, https://doi.org/10.1111/j.19331592.2006.tb00582.x The Republics Second Question Answered 263 we can know that they are systematically misleading and that the way things appear is not the way things really are. The upshot of all this is that, appearances to the contrary notwithstanding, the just persons life is happier than the unjust personsin fact, it is 729 times happier, if Socrates geometric proof is to be believed. The tyrant, he reasons, is, counting himself, three times removed from the oligarch: tyrantdemocratoligarch. And the oligarch is three times removed from the aristocrat. Three times three is nine, which cubedthat is, three-dimensionalizedmakes the aristocrat 729 times happier than the tyrant. As with the perfect number at the start of Book VIII, I am not sure that Plato intends this to be taken seriously; I am inclined to take it as a joke, and, like most philosophical jokes it is not especially funny. I suggest that we think of it as Platos way of suggesting that the contest between the just and unjust lives is not even close: the just life is way happier than the unjust life. The Metaphysical Elevator and the Metaphysics of Pleasure As many readers will expect, there is a major worry about the Metaphysics of Pleasure Argument. It is not a logical worry, since the Metaphysics of Pleasure Argument is valid: its conclusion must be true if its premises are true. But its soundnessthat is, the question of whether its premises are actually true, given that it is validis another matter. P3, that the objects of the rational pleasuresthe Formsare more real than the objects of the spirited pleasures and the appetitive pleasuresconcrete particularsis not obviously true, and indeed for many readers it is obviously not true. P3 is true only if Platos Metaphysical Elevator goes all the way to Level Four, where the Forms are not only mind-independently real but are more real than the many particular things that are instances of them. Even going to Level Three, where the Forms are mind-independently real, is not enough to make P3 true, and many readers will balk at going even to this level. More readers, I suspect, will get off the Elevator at the second floor, insisting that the Forms are human constructs and that the concrete particular things are more real than the Forms so conceived, since the Forms so 264 Platos Republic: An Introduction conceived are mind-dependent entities while the particulars are not. For these readers, P3 should be replaced with: P3* The objects of the appetitive pleasures are more real than the objects of the spirited pleasures and the rational pleasures. This yields these conclusions: C1* Therefore, appetitive pleasures are more filling than spirited and rational pleasures. (From P1, P3*) C2* Therefore, appetitive pleasures are more pleasant than spirited and rational pleasures. (From P2, C1*) This better fits with the commonsensical views that eating a donut is more pleasurable, because more filling, than grasping the Form of the donut and thus understanding the essence of donut-ness, and that sexual pleasure is more pleasant than philosophical pleasure. Perhaps Socrates was wrong to focus on quantity rather than quality. Many readers might concede that while appetitive pleasures are more pleasant than rational pleasures, rational pleasures are better, higher quality pleasures than appetitive pleasures, as they appeal to our higher nature as rational creatures. But this is expressly not what Socrates is arguing. Even readers inclined to think that Platos theory of the Forms is right and thus to take the Metaphysical Elevator all the way to the fourth floor should concede that, at least in the Republic, Plato has not provided good reasons to believe in the Forms. The argument that supports his two-worlds metaphysics, the Powers Argument, is logically invalid, and even if this invalidity can be fixed, we have good reason to doubt that knowledge and belief have different objects. This casts a long, dark shadow across the Republic. Socrates regards the Metaphysics of Pleasure Argument as the greatest and most decisive (9.583b) in answering the Republics second question, but it depends for its soundness on the problematic Powers Argument. So even if we agree with Socrates that the just life is happierperhaps even 729 times happierthan the unjust life, we will have to concede that he has not really given Glaucon and Adeimantus what they asked of him, a justification for this belief. The Republics Second Question Answered 265 Argument #3: an image of the soul in words (9.588b590e) Given the dependence of the Metaphysics of Pleasure Argument on the Powers Argument, things look bleak for Socrates view that the just life is happier than the unjust life. But Plato follows up the philosophically abstract Metaphysics of Pleasure Argument with an intuitive metaphor that he does not officially count as an argumenthence the but which seems more powerful than the supposedly decisive argument he just gave, and not merely because it does not depend in any way on the contentious metaphysics of the Forms. To argue against the view that the unjust but seemingly just life is happier, Socrates offers an image of the soul in words (9.588b). Perhaps this is Platos way of indicating that he understands that the Metaphysics of Pleasure Argument will not persuade skeptics unconvinced of the reality of the Forms. Or perhaps it is a subtle way of reminding us that we are in the Cave, where images and shadows are the cognitive coin of the realm. Imagine first a multicolored beast (9.588c) with many heads, some the heads of gentle animals, others more savage. Multicolored translates [poikilos], a nod to the multicolored garment that is worn by the defective democratic polis in Book VIII. Then imagine a lion, smaller than the beast, and last a human being, smallest of the three. Then join these three so that they grow together naturally (9.588d): the resulting creature is not mere artifice, a jumble of separate parts having nothing to do with each other, but something that functions as an integrated organism. Finally, cloak them in a human exterior, so anyone aware only of the exterior will think the creature a human being. The analogy is fairly straightforward: the multiform beast represents the appetites, the lion represents the spirited part of the soul, and the inner human being represents reason. Now, Socrates argues, when someone who maintains that injustice is more profitable, better for you than justice, what they are telling you, is that you are better off feeding the beast, starving the human, and getting the lion to do the beasts bidding. But no one would think that is prudent. To claim that the unjust life is happier implies something falsenamely, that you are better off feeding the voracious, multiform beast and starving reason so it follows that the unjust life is not happier than the just life. 266 Platos Republic: An Introduction It is perhaps surprising that Socrates argues that one should not starve the beast, but earlier he indicated that the philosopher neither starves nor feasts his appetites (9.571e) in his nighttime ritual to keep his dreams free of lawless, unnecessary appetites. Nor should we let the beasts different parts attack and kill each other. Though Plato would likely agree with Immanuel Kants view that it must be [] the universal wish of every rational being to be altogether free of them5 our appetites are not going anywhere, at least not as long as we inhabit a body. The beast is part of us. So we should bring our parts into harmony with each other, as much as possible, accustoming them to each other and making them friendly (9.589a). In living a just life we tend the beast as a farmer cares for their animals, domesticating some and separating and containing the feral ones. It is a compelling picture in many ways, but Socrates takes it even further. Someone who lives unjustly is enslaving the best part of himself, reason, to feed the worst, appetite. When the financial rewards are great enough, that might seem a bargain worth striking. But no one, Socrates argues, would enslave his children to savage and evil men (9.589d); there is no amount of money that would make that a good deal: it would not profit him, no matter how much gold he got (9.589e). Why, then, are we willing to treat ourselves so poorly, in ways we cannot imagine treating those we love? It is a fascinating insight. What philosophers sometimes call self-other asymmetry usually involves our problematically treating ourselves better than we treat others. Virtues and moral reasons are often correctives to this egoistic tendency to think our interests count for more than the interests of others. While some advocate altruism, the view that our interests count for less than the interests of others, correcting egoism requires only the egalitarian view that everyones interests have the same weightthat self and other are symmetric. What is so interesting about Platos point here is the suggestion that the self-other asymmetry at work when we are trying to determine which whole way of life would make living most worthwhile for each of us (1.344e) is one in which we give our interests, at least our true interests, less weight than we should. I suspect that this will resonate with many readers. If I have promised a friend to meet for an early morning bike ride, it is extremely unlikely 5 Immanuel Kant, Groundwork of the Metaphysics of Morals, p. 40 [Ak. 4:428]. The Republics Second Question Answered 267 that I will roll over and go back to sleep when the alarm wakes me. But if it is a promise I have made only to myself, well, if it is a cold and dark morning there is a decent chance that I will turn the alarm off and stay in bed. If I would never casually blow off a commitment made to a friend, why would I do so when it is one I have made to myself? If reason fully governed my soul, my appetites for sloth and comfort would have been tamed by reason and its ally, spirit. Readers tempted to judge themselves harshly on this issue should take some comfort from the fact that Marcus Aurelius, the great Stoic and indeed the Emperor of Rome, often wanted to stay in bed, too, and tried to have arguments at the ready to rouse himself (Meditations 5.1). One great advantage of Socrates analogy is that it does not presuppose the problematic theory of the Forms. It is simple and intuitive, as the best analogies are. It is not without objection, however. As mentioned much earlier, the great eighteenth-century Scottish philosopher David Hume thought that philosophers regularly overstated the claims of reason; Hume thought that reason was but the slave of the passions, so he would be skeptical of the ideal person Plato has sketched here. So too would Epicurus, whose taxonomy of desire we explored in the last chapter. Neither of these philosophers advocated egoism and injustice, but neither had the lofty view of reason that one finds in Plato in particular and in the Western philosophical tradition in general. It is worth noting that much contemporary psychology sides with Hume and Epicurus against Plato and most of the Western philosophical tradition. Reason, the eminent social psychologist Jonathan Haidt argues, is like someone riding an elephant; only a fool could think they are in charge of the elephant. But they can learn the elephants ways, learn that there is wisdom in the emotions, and use their rationality to guide the elephant toward the goals it naturally has. So even if we are skeptical of the role Plato assigns to reason, we might find a modified version of this analogical argument plausible, one in which the inner human being is constituted not by pure reason but by emotions such as compassion, care, and love. And we might well wonder, too, if what Hume called a sensible knavesomeone who generally acts justly but cheats when they can do so without detectionwould be persuaded, and indeed if we should be persuaded, that the just persons life is more pleasant than the sensible knaves. Socrates argument seems 268 Platos Republic: An Introduction plausible against the tyrant but perhaps this is only because a reasongoverned philosopher-king will always fare better than the manic basket of addictions, neuroses, and psychoses that is the tyrant. But how a philosopher-king would fare against someone who is decent but cuts corners (perhaps when the harm he does is not significant and the gain to him vastly outweighs it) is another matter. Socrates insists that the unjust persons injustice can remain undiscovered only for so long, and while we can think of examples confirming this claimoff the top of my head, I offer Lance Armstrong, Bernie Madoff, and any number of politicians who are brought down by scandalsit is worth noting that this is spurious evidence for Socrates claim. That we can list unjust people whose injustice has been discovered does not provide reasons for thinking that there cannot be unjust people whose injustice remains undiscovered. It may well be that the just person and the sensible knave have incompatible conceptions of happiness. Paternalism (9.590d) So the just life, which for Plato is the life in which reason governs the soul, is significantly happier than the unjust life. It may not always be the happiest possible life, since, as we have seen, living in an unjust or a non-just polis precludes full happiness. So justice, while necessary for happiness, is not by itself sufficient for it (something Stoicism, which began around 300 bce and which is currently enjoying a renaissance in our troubled age, disagrees with, taking virtue to be sufficient for happiness). We have noted on several occasions Platos insistence that the majority cannot be philosophic (6.494a). Most of us are not capable of grasping the Form of the good, Plato thinks, so most of us are not capable of acquiring the personal virtue of wisdom. We may have true beliefs about what is best for our souls, but by our natures we lack the capacity for knowledge in this area. But if that is the case, how can the non-philosophers among us be happy? It seems that most of us are doomed to live unhappy lives. Is there any way to escape this pessimistic conclusion? There is, Plato thinksthough his solution is unlikely to be attractive to most readers. Since most of us cannot be ruled by our own power The Republics Second Question Answered 269 of reason, it is best that we be ruled by the philosopher-kings (and -queens) reason: Therefore, to insure that someone like that is ruled by something similar to what rules the best person, we say that he ought to be the slave of that best person who has a divine ruler within himself. It is not to harm the slave that we say he must be ruled [] but because it is better for everyone to be ruled by divine reason, preferably within himself and his own, otherwise imposed from without, so that as far as possible all will be alike and friends, governed by the same thing. (9.590cd) Even if Plato means slave ( [doulos]) only metaphorically, many if not most readers will reject this out of hand. Most readers, I suspect, are liberalsnot in the contemporary American political sense of voting Democratic instead of Republican, but in the philosophical sense of valuing liberty over wellbeing. Paternalists prioritize wellbeing over liberty where the two conflict, holding that interfering with another persons liberty or autonomy is justified if the interference benefits the person being interfered with. Philosophical liberals, by contrast, typically hold that the only justification for interfering with someones liberty is to prevent harm to another person; if my conduct harms only me or is harmless but regarded as immoral, the liberal argues, neither the state nor another person is justified in interfering. Of course, if I am not in my right mind or if I am lacking vital information, most liberals will countenance temporary interference. If I do not know that the bridge ahead is out, the liberal might try to stop me from bicycling across it but only to make sure that I am aware of this materially relevant fact or that my judgment is not impaired. If I know that the bridge is out for me, the whole point is to try to jump across the missing spanthe liberal will not think interfering is justified. It is not surprising that Plato endorses paternalism. But most Americans, I think, take liberalism (in the philosophical sense) for granted, at least to a significant degree. Most of us, I suspect, share John Stuart Mills view that the only purpose for which power can rightfully be exercised over any member of a civilized community, against his will, is to prevent harm to others.6 One of Mills arguments 6 John Stuart Mill, On Liberty, ed. by Elizabeth Rappaport (Indianapolis: Hackett Publishing, 1978), p. 9. 270 Platos Republic: An Introduction for this view is that paternalism does not work: given the centrality of autonomy and spontaneity to the conception of happiness many of us share, outside interference for our own good will likely backfire, since the resentment we feel at being interfered with will outweigh the good that the interference does. We can probably think of cases where Mill is mistaken, especially where the benefit done is significant and the interference is minimal, as in seatbelt laws. Many readers will think Mills argument is beside the point, holding that interfering with a competent adult for that adults benefit is wrong in itself, regardless of any beneficial consequences, since paternalism manifests a failure of respect. We interfere with our and even others children when doing so is required to protect the children from themselves. But adults are another matter entirely. We will not adjudicate this dispute between liberalism and paternalism here; I raise it largely to give readers a framework and vocabulary with which to agree or disagree with Plato. To justify the belief that, fundamentally, liberty trumps wellbeing, may prove more difficult than even die-hard liberals imagine. And it may be that our shared ideology shapes our views on questions like this in a non-rational way. Many readers are familiar with Patrick Henrys saying Give me liberty or give me death!, and many of us know that New Hampshires license plate reads Live Free or Die (which, admittedly, makes Wisconsins motto, Americas Dairyland, sound pretty tame). But, like Glaucon and Adeimantus, our task as rational creatures is to think through these core values and to try to find good reasons to justify what we already believe. Of course, we may fail, or we may change our minds, perhaps thinking that the liberal, individualistic conception of happiness that grounds our objections to Platos paternalism is, if not a silly, adolescent idea of happiness (5.466b), one we no longer fully endorse after reflection. Platos paternalism is fueled by, among other things, his antiegalitarian belief that most people are incapable of wisdom as well as his highly demanding conception of what counts as knowledge. Some readers will be skeptical that we can ever know what is best, in Platos sense, insisting that the best we can do is to have justified beliefs about how to live, and that views very much at odds with each other might be justified. Such readers may insist that the intellectual virtues of humility and open-mindedness are crucial to thinking about how to The Republics Second Question Answered 271 live well, and that while Plato has challenged them to think through some of their fundamental values and presuppositions, he has not succeeded in convincing them that those values are mistaken and those presuppositions are false. At best, Platos arguments seem to provide a reason for those who already find themselves in agreement with their conclusionbut that does not render wrestling with the Republic a worthless, circular enterprise. Even if ones reasons for living justly will not convince the Thrasymachuses of the world, it is valuable to ensure that our beliefs form as consistent a set as possible. Most of us, I suspect, are more like Glaucon and Adeimantus than we are like Thrasymachus (though we probably all have a bit of him in us), who want Socrates to show them that their belief that the just life is happier is justified or at the very least not foolish, wishful thinking. It would be nice if egoists found these reasons persuasive, but that may be asking too much of philosophy. Plato and Socrates thought philosophy could do this, but we have seen over and over that their arguments fall well short of the mark and that only people who share their fundamental assumptions (e.g., about the Forms) will find their arguments persuasive. Even so, those of us who do not share those fundamental assumptions can find their arguments intriguing and worthy of the time and attention of reflective people who take seriously the question of how to live their lives. Some Suggestions for Further Reading Readers interested in exploring the philosophy of friendship will find no better place to start than with Books 8 and 9 of Aristotles Nicomachean Ethics, which they will find, along with other excellent readings, in Other Selves: Philosophers on Friendship, ed. by Michael Pakaluk (Indianapolis: Hackett Publishing, 1991). Readers will find Laurence Thomas excellent essay, Friendship and Other Loves and others in Friendship: A Philosophical Reader, ed. by Neera Badhwar (Ithaca: Cornell University Press, 1993). Readers interested in Mills distinction between higher and lower pleasures will find it discussed in Chapter Two of John Stuart Mill, 272 Platos Republic: An Introduction Utilitarianism, 2nd ed., ed. by George Sher (Indianapolis: Hackett Publishing, 2002), pp. 811. Matthew Crawford, Shop Class as Soulcraft (New York: Penguin Books, 2010) is an excellent discussion of, among other things, the role reason plays in the manual arts, offering a powerful antidote to Platos views from a Ph.D. philosopher who repairs vintage motorcycles for a living. Readers interested in a leading psychologists take on the role reason plays in a happy life should start with Jonathan Haidt, The Happiness Hypothesis: Finding Modern Truth in Ancient Wisdom (New York: Basic Books, 2006). Readers interested in philosophical or legal liberalism would do well to start with John Stuart Mill, On Liberty, ed. by Elizabeth Rappaport (Indianapolis: Hackett Publishing, 1978). For an interesting collection of essays on paternalism, readers might have a look at Paternalism, ed. by Rolf Sartorius (Minneapolis: University of Minnesota Press, 1984). Readers interested in a brief musical exploration of the multicolored beast who dwells within should listen to Nick Lowe, The Beast in Me, on Quiet Please... The New Best of Nick Lowe (Yep Roc Records, 2009). Muse tuning two kitharai. Detail of the interior from an Attic white-ground cup (c. 470460 BCE). Photograph by Jastrow (2006), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/ File:Muse_lyre_Louvre_CA482.jpg#/media/File:Muse_lyre_Louvre_ CA482.jpg 14. Are We There Yet?: Tying up Loose Ends in Book X Book IX ends with Socrates telling Glaucon that if the polis one lives in is far from ideal, even if the ideal polis exists only in theory but not in reality, one can still make himself its citizen (9.592b), and thus learn to live justly in an unjust or a non-just world. It would be a fine place to end the Republic, but Plato has other ideas. Three of them, in fact. The Ancient Quarrel between Poetry and Philosophy (10.595a608b) The first of these is tying up a loose end regarding poetry in the ideal polis. Since the restrictions on poetic form and content developed in Books II and III preceded the division of the soul in Book IV, Socrates thinks it would now be fruitful to revisit the status of poetry, armed with an account (logos) of the soul (psuch)a psychologyhe lacked earlier. He argues that the three-part soul further confirms the earlier conclusion that imitative [] poetry should be altogether excluded (10.595a) from the ideal polis. Readers who think they have misremembered the earlier discussion should feel free to indulge in an its not me, its you moment, for it is Socrates whose memory seems faulty. Earlier, Socrates allowed imitations of the words or actions of a good man (3.396c) and of someone engaged in peaceful, unforced, voluntary action [] acting with moderation and self-control (3.399ab), not to mention modes and rhythms that would suitably imitate the tone and rhythm of a courageous person who is Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.14 276 Platos Republic: An Introduction active in battle (3.399a). A lot has happened in the Republic since Book III, so perhaps we can forgive Socrates misremembering his earlier view. It may be that Plato is poking a little fun at Socrates here, for at least half a dozen times in Book VI we are told one must possess the intellectual virtue of having a good memory to be a true philosopher. Socrates target is narrower than is frequently claimed. He is not arguing against poetry (or, even more broadly, art) in general but rather against imitative poetryand indeed it is even narrower than this: he wants to exclude poetry that aims at pleasure and imitation (10.607c) from the ideal polis, which would leave room for imitative poetry that aims not at pleasure but at moral improvement. The ideal city can, then, employ a more austere and less pleasure-giving poet and storyteller, one who would imitate the speech of a decent person (3.398a). In arguing that would-be guardians should not be imitative ( [mimtikos]) (3.394e), Socrates is really arguing that guardians should not be imitatively promiscuous: they should not be able, willing, or disposed to imitate any and every type of character, since this would prevent them from cultivating the sense of shame and disgust at dishonorable action that is the basis of good character. Since imitations practiced from youth become part of [ones] nature and settle into habits of gesture, voice, and thought (3.395d), Socrates is very leery of imitative promiscuity. That all poetry inspired by the pleasure-seeking Muse (10.607a) must be excluded from the ideal polis is a conclusion that Socrates comes to reluctantly. He loves poetry, especially Homer, and is loath to live without it. There is no Homer or Hesiod, no Aeschylus or Sophocles or Euripides in the ideal polis. Instead, hymns to the gods and eulogies to good people are the only poetry we can admit into our city (10.607a) which, interestingly, is the only kind of poetry one encounters in the first, rustic city (2.372b). It is as though Socrates looks longingly at a copy of the Iliad, weepily confessing, I cant quit you. But quit it he must, for his commitment to philosophy is a commitment to going whatever direction the argument blows us (3.394d), even when we do not like the destination or find the winds too strong. We might expect Glaucon, who objected to life in the rustic first city because the food was too simple, to object to the absence of a key cultural and aesthetic staple, but he finds Socrates arguments so compelling that he makes no objections to the restricted poetic diet Socrates prescribes. Are We There Yet? 277 Our task as readers is to determine if we find Socrates arguments as compelling as he and his audience do. Since the arguments are overlapping and interrelated, separating them into distinct arguments is somewhat artificial, but doing so aids in clarity, so I will divide the arguments into three. The Metaphysical Argument: Art Merely Makes Copies of Copies, and Thus is not Worth Taking Seriously I have dubbed the first argument metaphysical since the Forms play a significant role in it. Perhaps surprisingly for an argument meant to support a conclusion about imitative poetry, Socrates focuses on painting more than poetry in the metaphysical argument. But we will see that painting more clearly makes the point he wants to establish against poetry. All beds, Socrates argues, have in common the Form of the bed itself: that essence that makes them beds rather than chairs or knives or sheep. Any particular bed that one might sleep in is a spatio-temporal copy of this Form, just as the shadows on the Cave wall are copies of the artifacts held before the fire, and just as those artifacts are ultimately themselves copies of the Forms that inhabit the sunlit intelligible world above. So someone who paints a bed is making a copy of something that is itself a copy. The painter is imitating the appearance of a bed, and indeed how it appears from a particular vantage point, not the reality or being of the bed: painting [] is an imitation of appearances [] [not] of truth (10.598b). Where the painter represents objects, the poet represents actions, but the argument is the same for both: paintings and poems are too metaphysically thin, too much like the shadows and reflections one sees on the wall of the Cave. Imitation is a kind of game, Socrates says, and not something to be taken seriously (10.602b). There is no hint here of the danger lurking in the games we play, as there is elsewhere in the Republic (e.g., 4.424d, 7.539b, 8.558b). His point is that anyone who could construct a bed would spend his or her time on these metaphysically more substantial objects; and anyone who could philosophically understand the Form of bedness would spend their time on this metaphysically more substantial task. Only someone 278 Platos Republic: An Introduction insufficiently skilled in either would waste their time on something so trivial as making art. Two recurring themes in Socrates animadversions against imitative art are worth bringing out here. The first is that he shows little if any interest in artistic skill. On the one hand, this makes sense, given his metaphysical views. But on the other, he simply ignores the skill required to make copies of copies. Whatever ones metaphysics, trompe loeil paintings and modern photo-realism are impressive in and of themselves; they need not be written off as trickery (10.602d) and bogus magic. A second, related theme is his lack of interest in the joy of artistic creation. This is perhaps a particular instance of a more general disregard for the importance of play in a well-lived and happy life. It is ironic, given the artistic care and skill with which Plato constructed the Republic, that its protagonist would be so uninterested in artistic creation. Earlier we criticized Socrates narrowness in asserting that there are three primary kinds of people (philosophic, victory-loving, and profit-loving (9.581c)), and here we can see yet another type to add to the list: artists, who devote their lives to artistic creation. Perhaps some of this emanates from a contempt for those who work with their own hands (8.565a), itself an odd thought from someone who is himself a stonemason. But this may be Platos upper-class snobbery more than anything. Artistic readers who have made it this far in the Republic often get righteouslyand rightfullyindignant or shake their heads in pity at this foolishness. It is not just that Socrates is not interested in and does not revere the products of artistic creation, but that he is not interested in the process of artistic creation and indeed denigrates it by likening it to walking around with a mirror (10.596d). Thus it is no surprise that he dismisses most painting and poetry as trivial wastes of time. One need not fully agree with Schillers dictum that one is fully human only in play to think Plato is missing something important here.1 Plays value is thoroughly instrumental for Plato, useful as a means of moral education, but in itself possessing no intrinsic value. Schillerand many readers, I suspectwould disagree. 1 Friedrich Schiller, On the Aesthetic Education of Man, trans. by Keith Tribe, ed. by Alexander Schmidt (New York: Penguin Books, 2016), p. 45 [Letter 15]. Are We There Yet? 279 The Epistemological Argument: Artists Literally Do Not Know What They Are Talking and Painting about Given the way metaphysics and epistemology are fused in the Republic, it should be no surprise that the next argument is intertwined with the metaphysical argument. Here, the worry is epistemological: that artists do not need knowledge of what they are imitating in order to imitate it. While it is true that the imitator needs to know how to imitate that appearance, such know-how is rather trivial, Socrates thinks, given the metaphysical thinness of what it results in. To make his epistemological point, Socrates contrasts the user, the maker, and the imitator of a flute. An expert flute-player knows what a good flute should sound like and what makes it play well. (Here, Socrates uses know in an ordinary sense, not the technical sense he established in Book V and developed in Books VI and VII.) The flutemaker, who has a correct belief about what a good flute is (having just had this explained to them by the expert flutist), sets about making a good flute. Socrates does not say, but presumably the flute-maker possesses knowledge about the effects of different kinds of wood, different drying times, etc. They know how to make a good flute; the flutist knows what a good flute isand this conceptual knowledge is always superior to practical know-how, for Socrates. An imitator, by contrast, has neither knowledge nor right opinion (10.602a) about good flutes. Knowledge and correct belief about what makes a flute good is not needed to paint a flute; what the artist hasignorancewill suffice for their purposes, which is imitating how flutes appear, not what they are. Given how important epistemology is to Plato, we can see why he is down on artists. But the epistemological argument is even more serious than this, as we see when we shift focus from painting to poetry. Just as one can paint a flute without knowing what a good flute is or what makes good flutes good, one can imitate images of virtue [] and [yet] have no grasp of the truth (10.600e). People look to Homer for moral guidance, but they should not, Socrates argues, since Homer does not know what courage, for example, is; he only knows how to create an image of it in poetic song. If Homer had really been able to educate people and make them better (10.600c), Socrates reasons, if Homer had been able to benefit people and make them more virtuous, his 280 Platos Republic: An Introduction companions would [not] have allowed either him or Hesiod to wander around as rhapsodes (10.600d). Instead, they would have insisted that Homer and Hesiod stay put and teach them about virtue, or they would have followed them in a caravan of moral education. And Homer, had he actually possessed such knowledge, would have surely obliged. But Homer and Hesiod were allowed to wander, so Socrates concludes that they did not possess genuine moral knowledge. While poets and painters might have good ears and eyes for what a culture takes virtue and the virtues to be, one of the lessons of the First Wave back in Book V was that we should not take our cultures norms at face value: it is foolish to take seriously any standard of what is fine and beautiful other than the good (5.452e). Socrates, of course, is not a relativist about norms, but neither is he a conservative, at least of the sort that gives great weight to tradition as a source of moral wisdom. That ones culture has long approved of certain values carries little or no epistemic weight for Socrates. One of philosophys tasks is to subject these values to rational scrutiny. We saw earlier that the ridiculousness of women wrestling naked and governing faded way in the face of what argument ( [logos]) showed to be the best (5.452d). A perhaps unexpected upshot of the image of the soul in words in Book IX is an objective test of ones cultures conventions about what is fine and what is shameful. Fine things, Socrates says, referring to things that are kalon, are those that subordinate the beastlike parts of our nature to the human [] shameful ones are those that enslave the gentle to the savage (9.589d). Someone friendly to the arts might concede that many artists lack philosophical knowledge of the nature of goodness and the virtues but they might also insist that many of these artists possess true beliefs about these topics and are not ignorant, as Socrates claims. But Socrates might reply that this leaves an essential problem untouchednamely, the epistemic authority his (and our) culture accords to artists. If they lack knowledge, why care what they have to say? Distracted by their multicolored (10.604e, 10.605a) productions, we think they can teach us how to livean assumption that may seem odd in our age of entertainmentbut they lack the knowledge required to do so. But if we are fools to follow them, the problem seems to be with us rather than them. Are We There Yet? 281 Even readers who are not persuaded by Socrates argument might concede that it points to something important, something perhaps more important in our day than in Socrates: the supposed authority of celebrities to pronounce upon issues of the day, especially political issues. Many of ustoo many of usfall for the argumentam ab celebritas, as we might call it. While we can revere them as actors, why should we take seriously the political pronouncements of Meryl Streep or Robert De Niro? They can teach us a great deal about the craft of acting, but is there any reason to think that they have a great deal to teach us about public policy? They might; but if they do, it is not because they are great actorsthat is, highly skilled at imitation. Many readers will not share Socrates expectation that artists teach us how to live; but readers of a serious, aesthetic bent will think that some novelists, poets, filmmakers, musicians, composers, etc. do aim for more than entertainment. Indeed, there is good reason to think of some artists as creating philosophical art: art that wrestles with some of the same moral, metaphysical, and epistemological problems that occupy philosophers. I suspect that many readers have a more expansive view of what constitutes philosophy and argument than Socrates does, and so are willing to take these artists views seriously. But even so we would do well to maintain a healthy dose of Socratic skepticism about the moral and epistemological authority many of us see them as having. We are all prone to confirmation bias, of thinking certain bits of evidence are good evidence because they confirm what we already believe. Holding our favorite artists feet to the philosophical fire and querying the views and arguments they offer is a show of respect for them as thinkers that is consistent with respecting them as creative artists. The upshot of the epistemological argument is that, even though one might really enjoy reading (or, more likely in the Greek world, listening to a performance of) Homer, one would be foolish to arrange ones whole life in accordance with his teachings (10.606e), since there is no good reason to think that poetic skill overlaps with philosophical insight. Thus we should not, as Polemarchus does in Book I, quote poets like Simonides as moral authorities on the nature of justice, for example. Instead, we should critically examine their sayings and adopt them as guides for living only if they pass rational muster. 282 Platos Republic: An Introduction The Moral Argument: Art Corrupts Even the Best of Us Some readers will have noticed a pattern in the Republic: Plato tends to list items in increasing order of importance; the third of three items is almost always the most important. The Third Wave is the biggest and most difficult one (5.472a) and the third argument that the just life is happier is the greatest and most decisive (9.583b). We see that pattern again here: the moral argument against art, to which we now turn, is the most serious charge against imitation (10.605c). In the first two arguments, the key notion of imitation ( mimsis]) seems roughly synonymous with representation: an object or action is re-presented by the painter or poet. But in this final argument we should keep in mind the more precise sense Socrates had in mind when he distinguished the content of poems and stories or what they say from how they say iti.e., their style. Imitation is a matter of mak[ing] oneself like someone else in voice or appearance (3.393c) and thus the poet or performer impersonates a character, speaking from that characters point of view, as that character would speak and actas actors do onstage. Imitation in this sense is contrasted with pure narration, in which the author or speaker describes but not does enact actions and events, telling the audience that a character said suchand-such but not directly quoting a characters speech (or if doing so, not attempting to imitate the speakers voice and mannerisms). Unlike the imitative poet, the purely narrative poet never hid[es] himself (3.393d) behind characters: the narrative poet is always present, never impersonating another and never being anything but themself. Socrates example is a non-poetic summary of the opening scene of the Iliad, a summary of events as one might find in a high school book report or in Cliff or Spark Notes. But narration is also the style of the hymns to the god of wine and fertility, Dionysus, known as dithyrambs, which were typically sung in the Phrygian mode, one of the two musical modes Socrates allows in the ideal polis (3.399a). So presumably dithyrambs are among the hymns to the gods that are allowed in the ideal city indeed, the citys poets will compose appropriate hymns (5.459e) to celebrate and consecrate the eugenic marriages discussed in Book V. A third kind of style is a mix of narration and imitation, which is the form epic poetry takes: a narrator tells the audience about certain events and Are We There Yet? 283 not merely quotes but enacts other events by imitating or impersonating some of the characters. In Book III Socrates focused on the moral danger imitation in the strict poses to performers, and presumably the creators of such poetry would also face moral danger as well. The title character in J. M. Coetzees Elizabeth Costello wrestles with something like this latter problem. Her concern is not with the perils of imitation but with the dangers that come with writing about profound evil. To do so well, one must confront evil deeply and indeed sympathetically, imaginatively entering into the consciousness of Himmler and Hitler and their ilk (which suggests a disagreement with the conclusion of Socrates epistemological argument). And she is not sure that writers who venture into the darker territories of the soul always return unscathed.2 In Book X Socrates shifts his attention away from the moral dangers that imitative poetry poses to its performers and toward the dangers it poses to the audience, who identify with the characters the performers impersonate. Where the epistemological argument focused on poetrys incapacity to make us better, the moral argument focuses on its power to make us worse: with a few rare exceptions it is able to corrupt even decent people (10.605c). We take seriously the sufferings of the protagonist and not only enjoy watching or listening but actually give ourselves up to following it (10.605d). Instead of being properly disgusted at the heros lamentations (an earlier focus of censorship, for example at 3.387d), we enjoy and even praise them (10.605e). But, Socrates argues, enjoying other peoples sufferings is necessarily transferred to our own (10.606b), and thus we nurture the pitying part of our soul, which, nourished by tragedy, destroys the rational [part] (10.605b). The problem is not merely that in taking our own sufferings seriously we forget that human affairs are not worth taking very seriously (10.604c), but rather that we dethrone reason from its rightful place and live lives guided by emotion when we hug the hurt part (10.604c)which prevents us from being just, and thus happy. Socrates arguments against comic poetry run parallel to his arguments against tragedy: instead of being overcome by grief, we are overcome by hilarity. Both involve a dethroning of reason 2 J. M. Coetzee, Elizabeth Costello (New York: Viking, 2003), p. 160. 284 Platos Republic: An Introduction which we think is temporary but which, Socrates thinks, is anything but. Whether we are giving ourselves over to laughter or lamentation, we are nourishing and nurturing the appetitive and spirited parts of our souls, which house the emotions, and we are unlikely to be able to contain this beast within when we leave the theater. It is telling that Socrates is especially concerned with imitative poetrys power to make us act, feel, and think differently in private than we do in public. He seems suspicious of and often hostile to privacy, which is unsurprising given the priority of the community over the individual that animates his thought. Socrates animus toward privacy pops up in various places. For example, that the guardians and auxiliaries have little to no privacy, living and eating communally and having no private property, fuels Adeimantus doubts about whether they can be happy. So Socrates concern about what we might call emotional privacy should not surprise us. A good person who has lost a child, for example, will be measured in his response to [his] pain [] and put up more resistance to it when his equals can see him [than] when he is alone by himself in solitude [] [where] he will venture to say and do lots of things that hed be ashamed to be heard saying or seen doing (10.603e4a). Socrates seems concerned that imitative poetry will encourage a kind of hypocrisy: in public, we will follow reason, which bids us to quietly bear misfortune, tempering our feelings of grief with protostoic thoughts that human affairs are not worth taking very seriously (10.604e), that what now seems like a tragedy might ultimately be for the best, etc.; but in private we will indulge and give vent to feelings of grief. It is no accident that the English word hypocrite derives from the Greek word for actor, (hupokrits), since hypocrisy involves pretense (and not mere inconsistency): hypocrites pretend to believe what in fact they do not, since appearing to believe certain things and acting in certain ways is in their self-interest. Socrates worry about the way imitative poetry works its dark magic in private is perhaps motivated more by simplicity and the unity of the soul as ideals of character than by a concern to avoid hypocrisy. A just man, we are told, is simple and noble and [] does not want to be believed to be good but to be so (2.361b). Although Thrasymachus thinks that Socrates just person is a sap exhibiting high-minded simplicity (1.348c), Socrates thinks of simplicity as integrity and purity, Are We There Yet? 285 in contrast with Thrasymachan duplicity and the specious multicolored attractions of the democratic constitution and character. The person who scorns imitations of excessive grief while at the theater but who indulges their grief at home, or who keeps a stiff upper lip in front of the children or the troops and then indulges their grief while in private, will not be of one mind (10.603c). Socrates insists that such a person is at war with himself (10.603c), his soul beset by civil war (10.603d) which of course has been a major concern throughout the Republic. But must a person whose emotional responses vary by context fail to achieve the virtue of one-mindedness? Socrates treats a persons expressing grief differently in different circumstances as cases of changing ones mind, but perhaps we should think of them instead as appropriately varying their responses to the differing demands of different situations. That Socrates wants more than a situation-specific, context-sensitive ethics was clear almost immediately in the Republic: since it is wrong to return the weapon to the deranged friend, returning what one has borrowed cannot be what justice is. But as we noted earlier, one may think that there are no universal ethical truths of the sort Socrates is after; perhaps the best we get are general principles or rules-of-thumb that give limited guidance and which must always be supplemented with situation-specific insight. (Something like this seems to have been Aristotles view.) We have already remarked on Socrates love for poetry, but it bears repeating. He loves poetry, but he thinks that it is a love for a dangerous object, one best avoided: we will behave like people who have fallen in love with someone but force themselves to stay away from him because they realize that their passion is not beneficial (10.607e). But since he lives in the actual world and not in his ideal polis, Socrates will keep his arguments against poetry ready to be chanted like an incantation when he encounters it (10.608a), like a drug to counteract it (10.595b). Up to this point, useful falsehoods (2.382c, 3.389b) have been the most prominent drugs in the Republic, prescribed by the guardianrulers most famously in the foundational myth of origin known as the Noble Falsehood (3.415b). Here the drug ( [pharmakon], from which English words like pharmacy and pharmaceutical derive) is knowledgetruth, rather than falsehoodand it is self-prescribed. It is as if Socrates recognizes an addiction to something that seems so 286 Platos Republic: An Introduction attractive and benign, but which is in fact insidiously harmful. It is a kind of self-help that seems to be available only to philosopher-kings and -queens; for the rest of us, the drug that the rational part of our souls can concoct is not strong enough, or, the souls rational part has been subordinated to the appetitive partthe part of the soul [] that hungers for the satisfaction of weeping and wailing (10.606a). In his Poetics, Aristotle famously disagrees with Platos assessment of tragic poetry, arguing that tragedy is actually good for us, achieving a catharsis ( [katharsis]) of pity and fear, the tragic emotions par excellence: A tragedy, then, is the imitation of an action that is serious [] in dramatic, not a narrative form, with incidents arousing pity and fear, wherewith to accomplish its catharsis of such emotions.3 Pity and fear, Aristotle argues in the last chapter of his Politics, exist very strongly in some souls, and have more or less influence over all,4 so we are benefitted when our souls are purged of pity and fear. Aristotle says surprisingly little about catharsis, given how frequently it takes center stage in discussions of his Poetics, and while this is not the place to explore it in any depth, a word or two is in order. Catharsis means cleansing or purification. Understood medically, catharsis is purgation, a process by which we are purged of harmful substances. But Aristotle, unlike Plato, does not think that emotions are in themselves harmful states that get in the way of virtue and are thus to be purged. For Aristotle, moral excellence [i.e., virtue] [] is concerned with passions and actions,5 and while reason governs a well-ordered soul, he thinks that many emotions and desires can be brought into harmony with reason, rather than being forever recalcitrant and in need of subjugation. Thus catharsis need not be exclusively a matter of purification by purgation; it can also be clarification by education. Consider the tragic emotion of pity, which is essentially directed at anothers unmerited distress. While Plato thinks that identifying with the tragic heros distress via pity will displace reason and thus lead to an unjust (or at least non-just) soul, Aristotle seems to think that it can lead us to appreciate our own vulnerability to the slings and arrows of outrageous fortune and to cultivate appropriate fellow-feeling and compassion. 3 Aristotle, Poetics, 6 1149b247. 4 Aristotle, Politics, VIII.6 1342a67. 5 Aristotle, Nicomachean Ethics, II.6 1106b16. Are We There Yet? 287 As the eminent contemporary philosopher Martha Nussbaum puts it, tragedy contributes to human self-understanding precisely through its exploration of the pitiable and the fearful.6 Far from being something to be purged from an ideal city, good tragedy should be welcomed, not because it is good entertainment or because good art enriches our lives, but because it contributes to the moral development and improvement of the citizensmuch as reading good literature might make us more empathic and more sensitive to moral nuance. It seems that Plato and Aristotle disagree about the value tragedy because they disagree about the value of our emotions, and indeed the value of our bodies. Socrates does not fear death, because his death means that his soul will at least be freed from the contamination of the bodys folly,7 which prevents the soul from encountering the pure reality of the Forms. Readers who share something like Aristotles attitude toward the emotionswhich shows that one need not be a full-blown romantic, giving absolute priority to emotion over reason, to value emotions positivelywill have good reason to be skeptical about Platos attitude toward imitative poetry. A Four-Part Soul? There is an additional problem with Socrates treatment of poetry that we ought to deal with. It is a problem that at first might seem hardly worth noticing, but which is potentially devastating to the project of the Republic. In dismissing imitation as a silly waste of time, Socrates focuses on the metaphysically thin nature of its objects: they are shadows on the cave wall, not to be taken seriously. This critique requires his twoworlds metaphysics, and we have already dwelled on the inadequacy of the support Socrates provides for this distinctive and bold metaphysical theory. But after attending to the shadowy nature of the products of imitative art, Socrates briefly turns his attention to the activity of perceiving these objects. He does not, as we might expect, refer back to the Divided Line, the lowest portion of which has artistic creations 6 Martha Nussbaum, The Fragility of Goodness: Luck and Ethics in Greek Tragedy and Philosophy (Cambridge, University of Cambridge Press, 1986), p. 390. 7 Phaedo, in Plato: Five Dialogues, trans. by G. M. A. Grube (Indianapolis: Hackett Publishing, 1981), p. 103 [67a]. 288 Platos Republic: An Introduction as its objects. Instead, he asks, on which of a persons parts does [imitation] exert its power? (10.602c) Both trompe loeil painting and ordinary optical illusions can lead us to false judgments about reality. My canoe paddle appears bent or fractured when it is submerged, but it is not; the lines of the Mller-Lyer illusion, discussed earlier, seem not to be the same length, but they are. Only measuring them reveals this, and measuring, like calculating and weighing, are rational activities, the work of the rational part of the soul (10.602d). So where do these potentially erroneous perceptions and perceptual beliefs come from? Since the part of the soul that forms a belief contrary to the measurements could not be the same as the part that believes in accord with them (10.603a), they cannot come from the rational part of the soul, given the Opposition Principle (4.436b). Nor does the spirited part of the soul provide a plausible home for perception. Perhaps perception is a function of the appetitive part. In another dialogue, the Theaetetus, Plato suggests this possibility and casts the net of perception widely, counting desires and fears as perceptions, along with more obvious examples like sight, hearing, smelling, feeling cold and feeling hot (156b). Not only do both perception and belief work with appetitemy desire for ice cream and my seeing (and believing) that there is some in the freezer together explain my reaching in to get somebut they have the same objects: I see the ice cream, I want the ice cream, etc. Still, it is not clear how perception can be a function of the appetitive part of the soul. Perceptions, like desires, are representations, pictures of the world, if you will. But they are pictures having different directions of fit, as philosophers sometimes say. Beliefs and perceptions are mental representations of the world that are supposed to match the way the world is; thus they have a mind-to-world direction of fit: the minds picture is supposed to match the world, and when they do not match, I need new beliefs and perceptionsI need a different picture. Appetites and desires, by contrast, have a world-to-mind direction of fit: they are representations not of how the world is but of how it ought to be or I would like it to be. So when the world does not fit my picture, I change the world to make it matchas if desires are skippered by Captain Picard of Star Trek: The Next Generation, with a make it so built into their very nature. Wanting more ice cream but seeing my bowl is empty, I go to the freezer and get some, so my picture of reality Are We There Yet? 289 (me eating ice cream) matches reality. (Of course, if one is inclined to Stoicism or Buddhism, one often tries to give up the unfulfilled desire, since it is the source of ones discontentment.) Thus it seems that there must be another part of the soul, one that forms (potentially erroneous) perceptual beliefsa fourth part of the soul, distinct from reason, spirit, and appetite. Okay, so there is another, fourth part of the soul. So what? What is the big deal? Well, the big deal is that the Republic turns on the analogy between the city and the soul: Socrates theorizes the ideal city not for its own sake but as a means to investigate the Republics two main questions. Back in Book IV all agreed that the same number and same kinds of classes as are in the city are also in the soul of each individual (4.441c), but the argument against imitative art now suggests that that agreement was a bad one, and that there is an important disanalogy between city and soul. Thus what followed from that agreementthe answers to the Republics two main questions about the nature and value of justiceare now called into question. Alas, neither Glaucon nor anyone else present objects to Socrates seeming to introduce a new part of the soul and to the problems this raises for the Republics central analogy. Perhaps this is another one of those places in which Plato is hoping his readers see a philosophical problem that eludes his characters. And perhaps he is making a point about the nature of philosophical inquiry: Socrates now has two views that seem to be in conflict with each other, and he needs to do more philosophical work to determine which view is more reasonable to retain. Readers will be forgiven for thinking that Socrates should have left well enough alone and ended things in Book IX. The Immortality of the Soul (10.608c614b) Having excluded almost all poetry from the ideal city, Socrates continues to tie up loose ends. Since the genuinely just but seemingly unjust life has been shown, he thinks, to be happier than the genuinely unjust but seemingly just life, we can now consider the consequences and rewards of justice. Adeimantus was especially adamant about excluding consideration of the reputational benefits of being thought of as just; too much of Athenian culture praised the rewards of being thought just, 290 Platos Republic: An Introduction ignoring justice itself. But now those rewards can be considered, and of course they incline in favor of the just life. But the philosophically most interesting part of the discussion concerns the benefits of being just that extend beyond this mortal coil and thus the claim that our souls are immortal. Earlier we emphasized that the concept of the soul at work in the Republic lacked the religious dimensions of the modern notion of the soul. But here is a place where they seem more similar than different. I imagine that many readers will agree with Socrates claim that each of us has a soul that will survive our bodily death. We will see in the final section of this chapter that Socrates account of the souls life after the death of the body differs significantly from religious conceptions involving eternal reward or damnation, this feature of its natureimmortalityis common to both. That the soul is immortal comes as news to Glaucon; more surprising still is Socrates claim that arguing for it is not difficult (10.608d). The argument is fairly straightforward and interestingly enough employs an inversion of the familiar Specialization Principle. Everything, Socrates argues, has a natural evil or badness that is proper or peculiar to it. Rot is the natural evil proper to wood, as blight is for grain and rust is for iron (10.608e). While we usually think of proper as a normative term with a positive valence, here it functions descriptively. If a thing is not destroyed by its proper evil, it cannot be destroyed by anything. Injustice, or vice more generally, is the souls proper evil, just as its proper good is justice; but while the soul is worsened by injustice, it is not destroyed by it. Therefore, the soul cannot be destroyed, and so it is immortal. Here is the argument, spelled out in premise-conclusion form: P1 Everything has a natural evil which worsens and corrupts it. (608e) P2 If something is worsened but not destroyed by its natural evil, then nothing else will destroy it. (609a) P3 Vice is the souls natural evil. (609b) P4 Vice worsens but does not destroy the soul. (609cd) C1 Therefore, the soul cannot be destroyed. P5 If something cannot be destroyed then it must always exist. (610e) Are We There Yet? P6 If something must always exist then it is immortal. (611a) C2 Therefore, the soul must always exist. C3 Therefore, the soul is immortal. 291 It is an interesting argument in many ways. The picture of the soul that emerges is of a thing that despite having parts is simple; the soul is not multicolored ( [poikilias]) (10.611b), which, we learned in the discussion of democracy, is a bad thing to be. Plato and Socrates value simplicity and unity over complexity and variety, which should come as no surprise by this point in the Republic. Nor, given the role reason plays in Platos thoughts, should we be surprised at the suggestion that the soul [] is maimed by its association with the body (10.611c). A soul is what you and I most fundamentally are, for Plato; we are not primarily bodies or body-soul unities. While the argument is logically valid, it is far from clear that it is sound, since P2 is not obviously true, and indeed seems obviously not true. Consider some of the examples Socrates employs to illustrate the idea of a proper evil: woods proper evil is rot; irons is rust. But clearly wood and iron can be destroyed by things other than rot and rust fire comes quickly to mind. So even if the soul cannot be destroyed by injustice, it is possible that it can be destroyed by an evil not proper to it. We might also question P4, the claim that injustice worsens but does not destroy the soul. The tyrannical person starves his rational part and not only takes no steps to domesticate the savage elements of his inner beast, but actually cultivates them and delights in their wildness. It is not at all implausible that such a paradigmatically unjust soul can destroy itself, consumed with that which it was nourished by, as Shakespeare says in Sonnet 73.8 It is not clear how seriously Plato intends this argument, especially given its rather obvious shortcomings. Its purpose may well be more strategic in a literary sense: it gets us thinking about life after death, which is the subject of the Republics finale, the Myth of Er. Rather than wring our hands or arch our eyebrows over the argument, let us turn to the 8 Shakespeares Sonnets, ed. by Katherine Duncan-Jones, The Arden Shakespeare, revised edition (London: Bloomsbury Publishing, 2010), p. 257. 292 Platos Republic: An Introduction Myth of Er, which is fascinating in itself, and a fascinating way for the Republic to end. The Myth of Er (10.614a21c) Why Plato ends the Republic not with an argument or an exhortation to the reader but with a myth is a question well worth pondering. Plato caps off the creation of the ideal polis with the Noble Falsehood, which suggests how important shared myths and stories are to political unity. His ending the Republic with a myth, especially after the many and various analogies and metaphors that populate the Republic, suggests the importance of myth and narrative to human self-understanding. Although philosopher-queens and -kings can subsist on an intellectual diet of theoretical argument, Adeimantus and the rest of us require that this diet be supplemented with the relish that stories provide. The myth concerns a man named Er, who recounts his after-death experiences as a messenger ( [angelon, whence our word angel]) to human beings (10.614d). Ers tale recounts what happens to our souls after they are separated from our bodies in deathhence the importance of the argument for the souls immortality. There are three distinct stages in the myth. In the first, Er finds himself in a beautiful meadow, near two pairs of openings, one pair to and from what lies below the earth; the other to and from the heavens. The souls of those who have acted unjustly are sent to the world below, incurring a tenfold penalty for each injustice. The souls of those who have acted justly go to the world above. The openings are busy with punished and rewarded souls ascending from the world below and descending from the world above, and souls of the recently deceased receiving their reward and punishment and thus ascending or descending. In the myths second stage, the returned souls travel to the place where the individuals fates are spun. I will not replicate Platos descriptions of the Fates, the Spindle of Necessity, and the entire scene, as I could not do them justice. The heart of this stage of the myth is a choice: each soul, whether it is returned from heavenly reward or heavenly punishment, chooses the life it will inhabit in its return to the world. Only for incurably wicked people (10.615e) is punishment eternal; and presumablythough Plato is mum on the topicthere is Are We There Yet? 293 eternal reward for the very best. But for everyone else, life after death is a matter of having a new bodily life. Although this part of the myth concerns the spinning of ones fate, it is crucial that each soul chooses its fate. When one chooses is determined by lot, so there is an element of randomness in the procedure, but each person will choose a life to which he will then be bound by necessity (10.617e). It is an interesting kind of necessity or determinism, very different from the causal determinism that contemporary philosophers concerned with free will tend to worry over. Rather, it is what we might call type determinism: a persons choices are determined by the type of person they are and will determine the type of person they will beand thus the kind of life they will lead. Hence the importance of choosing well. And here, Socrates tells Glaucon, is the greatest danger (10.618b), given that the souls choice of a life determines to a great extent how happy or unhappy that life will be. Thus we see the importance of the Republics second question: a persons answer to this question determines the kind of life they will lead. We need to choose carefully, and not be dazzled by exteriors, which may prove to be false faades. The first person to choose chose [his life] without adequate examination (10.619b); dazzled by wealth and pomp, he chose the life of a great tyrant, not realizing until after the choice was made that he was fated to eat his own childrena fate that might well be worse than death. His reaction is instructive: he blamed chance [] and everything else [] but himself (10.619c). Blaming others for the results of our own poor choices is a profoundly human reaction, it seems to me. In Genesis, Adam blames Eve for suggesting they eat the apple, and Eve blames the serpent. The irony here is that this chooser had returned from a life in heaven, his reward for having lived a virtuous life, though he had been virtuous through habit and without philosophy (10.619d). That is, he was conventionally good but unreflective, which, Socrates argues, left him vulnerable to poor choices. His goodness, like Cephalus, was more a matter of luck and circumstance than of a firm inner state of his soul, and ironically it is the cause of his undoing. The account of the various lives chosen is fascinating, with many people choosing to live an animals life, and with almost everyones choice depend[ing] upon the character of their former life (10.620a). The most instructive choice is probably Odysseus. He was among the 294 Platos Republic: An Introduction last to choose, though there remained many kinds of lives to choose from. He scoured the possibilities for the life of a private individual who did his own work (10.620c), insisting that he would have chosen this same life had he been first to choose. What Odysseus has chosen is, of course, a just life. That it was lying off somewhere neglected by the others (10.620c) is no surprise; since most of us are easily dazzled by multicolored exteriors and do not have a good grasp of the essence of justice and its necessity for a happy life, it is no wonder that it is not the one most of us choose. In the myths last stage, the souls, whose fates are now spun irreversibly, are brought to the Plain of Forgetfulness and the River of Unheeding, where they forget their choice and then re-enter the world. Like most myths, the Myth of Er is best not taken literally. Its point, I take it, is that while we each have a natural bent, which is then developed in various ways by the kind of nurturing we receive from our educations, our cultures, and the constitutions we live under, whether we are happy or not depends to a great extent on the choices we make. Most of our choices are not as dramatic or as momentous as the one-off choices depicted in the Myth of Er. Instead, they are daily choices, some large, some small, which shape our characters. In an anticipation of Aristotles doctrine of the mean, according to which every virtue is a mean between two vices (so courage is a mean between cowardice and recklessness, for example), Socrates suggests that a good choice is one in which we choose the mean [ and] avoid either of the extremes (10.619a). We should make our choices carefully, after due deliberation. Indeed, we should make choices, not act on impulse like the fickle democrat discussed earlier. A wise person chooses [a life] rationally and lives it seriously (10.619b). There are fascinating issues here, which we can do no more than touch on. Given that our nature and nurture largely determine which options will seem sensible and be appealing to us, even though each individual makes life-shaping choices, it is not clear how free those choices are. And if indeed they are not free (or not sufficiently free) as they seem not to be if type determinism is truethen readers may well wonder to what extent it makes sense to hold each other morally responsible for the choices we make and the actions we undertake. The Are We There Yet? 295 great twentieth-century philosopher Peter Strawson famously argued that holding ourselves and others accountable is so central to being human, there is little chance that we could give it up, even if we believe determinism to be true. Or, one might argue that although we are not fully responsible for the choices we make, perhaps we are responsible enough to warrant holding each other accountable. This issue, though Aristotle briefly considers it in his Nicomachean Ethics, seems more a modern than an ancient concern, so we should not fault Plato for not addressing it. Still, it is something that interested, philosophically inclined readers will want to explore further. Perhaps the most fascinating thing about the Myth of Er is that Plato chooses to end the Republic with it. Readers will notice the abruptness with which the Republic ends. The Republic begins with Socrates narration: on his way back to town with Glaucon, he meets Polemarchus; he tells someonewhom he is speaking to is never made clearabout the long philosophical discussion that took place at the house of Polemarchus father, Cephalus, a discussion which concludes with the Myth of Er. Plato reminds us of this by having Socrates address Glaucon directly in the Republics concluding paragraph. But conspicuous by its absence is something that would close the book, so to speak, on the book that is the Republic. There is no and then, exhausted, I went home or and then we had a sumptuous meal or anything that closes the narrative. I suspect that this is Platos taking his last opportunity to make a philosophical point with a literary device that is analogous to a sudden cut to black, as in the much-discussed final episode of The Sopranos. Earlier we observed how the opening of Book V echoes the opening of Book I; I suggested that this is Platos way of making a substantive philosophical pointthat philosophy is always returning to its beginnings, always starting over and reexamining its foundations. Here, I suspect, the point is similar, but about endings and conclusions rather than premises and beginnings. In not having a conclusive ending to the Republic, Plato seems to be telling us that philosophy never ends, that the conversation Socrates had at Cephalus house does not end, but continues every time a reader engages with the Republic, as we have done here. 296 Platos Republic: An Introduction Some Suggestions for Further Reading There is a large literature on Platos attitude toward poetry. G. R. F. Ferrari, Plato and Poetry, in The Cambridge History of Literary Criticism, vol. 1, ed. by George A. Kennedy (New York: Cambridge University Press, 1989), pp. 92148 is especially insightful and helpful. Readers who enjoy historical fiction may want to read Mary Renault, The Praise Singer (New York: Vintage, 2003), an excellent and moving novel about Simonides, the lyric poet Polemarchus quotes in Book I. Eric Brown, A Defense of Platos Argument for the Immortality of the Soul at Republic X 608c611a, Apeiron, 30 (1997), 21138, is a sympathetic reconstruction and defense of the argument for the souls immortality discussed in this chapter. Readers interested in the Myth of Er will find an extended discussion in Stephen Halliwell, The Life-and-Death Journey of the Soul: Interpreting the Myth of Er, in The Cambridge Companion to Platos Republic, ed. by G. R. F. Ferrari (New York: Cambridge University Press, 2007), https://doi. org/10.1017/ccol0521839637, pp. 44473. Readers interested in a contemporary discussion of free will and determinism will find Robert Kane, A Contemporary Introduction to Free Will (New York: Oxford University Press, 2005) an excellent place to begin. Readers interested in the idea of direction-of-fit might start with its source: G. E. M. Anscombe, Intention, 2nd ed. (Cambridge, MA: Harvard University Press, 2000), esp. pp. 567 ( 32). Head of Platon, Roman copy. Photograph by Bibi Saint-Pol (2007), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/ File:Head_Platon_Glyptothek_Munich_548.jpg#/media/File:Head_ Platon_Glyptothek_Munich_548.jpg Afterword Having travelled so great a distance together, a few words about our journey seem in order. Few readers, I suspect, will want to live in Platos ideal polisand they will be in good company, if a recent biography of Socrates is to be believed: We can be in absolutely no doubt that Socrates would have disliked and disapproved of the republic Plato wanted to bring into being.1 Whatever its virtues, it is too lacking in individual liberty to suit most of us. Most of us will side with John Stuart Mill over Plato, and regard the free development of individuality [as] one of the leading essentials of wellbeing.2 Platos utopia is far too much on the communitarian side of the spectrum for our comfort. We can set to one side the historical unlikelihood of the sort of aristocracy that Plato imagines; we are all familiarthough thankfully, for most of us, not in a first-hand waywith the evils of totalitarianism. The issue is more philosophical than that. Although romantics will demur at enthroning reason, many readers will agree that it is better for everyone to be ruled by divine reason, preferably within himself and his own (9.590e), but many of these will insist that preferably [] his own is too weak and will deny to their dying breaths that this reason may permissibly be imposed from without. Most readers will prefer a life in which they make their own choices to one in which their choices are made for themeven when they acknowledge that their own choices are often poor. Mill argues that the evils of paternalismof interference with the choices of others for their own goodfar outweigh its benefits. But one need not appeal to the consequences to be committed to the priority 1 Paul Johnson, Socrates: A Man for Our Times (New York: Penguin Books, 2011), p. 93. 2 Mill, On Liberty, p. 69. Sean McAleer, CC BY 4.0 https://doi.org/10.11647/OBP.0229.15 300 Platos Republic: An Introduction of liberty and autonomy over wellbeing. One might, like Kant, take it to be a matter of respect for human dignity, which is grounded in our capacity to make choices, to deliberate and decide and then to act. We are justified in interfering, says the anti-paternalistic individualist, only where our choices harm others. But even for such individualistically inclined readers, the Republic can offer salutary lessons. For while the pendulum swings too far to the communitarian end of the line in the ideal polis, one might concede that it swings too far to the individualistic side in, say, contemporary American culture. Perhaps we would do better to be more mindful of the good of the whole, to see our politics not as a means for advancing narrow individual and special interests but rather as a way to promote the general welfare. Platos anti-individualistic and anti-democratic animus is often expressed in his disdain for diversity and variety and complicationwith things that are multicolored ( [poikilos]), as he often puts it. Too much variety in poetic meter is frowned upon (3.399e), as is medical treatment that is too complicated (4.426a). And of course, democracys multicolored constitution is the source of its specious beauty (8.557c), as are its multicolored pleasures (8.559d) and the cast of characters that are its citizens, characters fine and multicolored (8.561e). And let us not forget about the multicolored beast (9.588c) that embodies our emotions and desires. While we need not value diversity for diversitys sake, taking diversity as an intrinsic good when its goodness is more properly instrumental, we need not think of it as an intrinsic bad, as Plato seems to do. A community can celebrate its diversity while at the same time celebrating and nurturing its unity. It can be one from manye pluribus unum, as it says somewhere or other. What is required for this is an attitude toward community and individuality that is more complex than Plato offers in the Republic. We can celebrate individuality and liberty while at the same time enabling individuals to be good team members, good cast members, etc. So while most of us do not accept Platos full embrace of the good of the community over that of the individual, we can incorporate more communitarian thinking into our lives and politics. Simply put, to think this is a matter of individualism versus communitarianism is to commit the all too common (and all too human) fallacy of the false dilemma. Afterword 301 Similar considerations can apply to other aspects of Platos thought where we recognize an important insight or truth that we do not feel comfortable taking fully on board. Consider justice as each person doing their own part and not meddling in the affairs of others. As we saw in Chapter Five, Confucius is in broad agreement with this, and one finds similar sentiments in the Bhagavad Gita: It is better to strive in ones own dharma than to succeed in the dharma of another. Nothing is ever lost in following ones own dharma, but competition in anothers dharma breeds fear and insecurity.3 Many readers will find that their peace and serenity and indeed their personal happiness increase as they strive to cultivate their own gardens, as Voltaire puts it toward the end of Candide, even though many of these readers will lament the political acquiescence they see in this idea. The trick, it seems, is to find the proper balanceto find when it is appropriate to mind ones own business, as it were, and when it is appropriate to demand and work for change. This, I think, is the task of practical wisdom, which functions not by applying abstract rules and principles but which, with principles operating in the background, assesses particular situations to see what each demands. There are many other instances of such topics in the Republic, and I hope to have brought enough of them to the surface for readers to do their own thinking about them. But there is one last big-picture consideration I must address before we end. The Republic is one of the great books of philosophy, but as we have seen, sometimes in perhaps excruciating detail, there are stretches where it is far from great philosophy. Its central argument, the Powers Argument of Book V, is fatally flawed, yet it is the only argument Plato gives us in the Republic in support of his distinctive, two-worlds metaphysics. While the Allegory of the Cave can survive at least in part without its support, the Sun and Divided Line analogies sink or swim with it, as their central point is to make sense of the distinction between the intelligible world of the Forms, where knowledge lives, and the visible world of particulars, the realm of belief. Moreover, the greatest and most decisive argument for the view that the just life is happier than the unjust life, the Metaphysics of Pleasure Argument, also depends on the Powers Argument. Socrates 3 Bhagavad Gita, trans. by Eknath Easwaran, 2nd ed. (Tomales, CA: Nilgiri Press, 2007), p. 108 [Chapter 3, verse 35]. 302 Platos Republic: An Introduction may be correct in giving the palm to the just life, but he has not adequately argued for this conclusion, so his belief in it would seem to be unjustified. Socrates recognized in Book I that he jumped the gun in thinking he had shown that the just life is happier than the unjust life when he had not yet determined what justice is. But having determined the nature of justice to his and his interlocutors satisfaction, he seems oblivious to the ways in which the Metaphysics of Pleasure Argument is fruit of the poisoned tree that is the Powers Argument. What gives? There is a tendency, to which I am prone, to think that this must be intentional on Platos part, that so smart a philosopher could not have unknowingly offered so poor an argument for so important a conclusion. Perhaps Plato took himself to be accurately reporting Socrates own argument rather than giving his own. Perhaps he recognized the arguments shortcomings and left uncovering them to his readers, in hope that theythat wewould notice them and become better philosophers as we tried to work them out. It is hard to know. The eminent philosopher and historian of early modern philosophy Jonathan Bennett, that rare bird who was as excellent a teacher as he was a philosopher, wrote in the preface to his first book on Kants Critique of Pure Reason: Like all great pioneering works in philosophy, the Critique is full of mistakes and confusions. It is a misunderstanding to think that a supreme philosopher cannot have erred badly and often: the Critique still has much to teach us, but it is wrong on nearly every page.4 Much the same could be said of Platos Republic. It might be scant comfort to some readers, but it seems to me to offer a powerful lesson on the point of doing and reading philosophy, which always requires doing it for oneself. Though Socratic wisdom consists in knowing that one does not know, it does not require giving up those beliefs one cannot justify. The key to being ethically justified in retaining these epistemically unjustified beliefs, it seems to me, is humility: we recognize them as not justified, perhaps as a result of our intellectual shortcomings, and continue to reflect upon them. There is a lot of cognitive space between nihilism and dogmatism. That so great a philosopher as Plato is frequently wrong is a testament to how hard it is to do philosophy well. 4 Jonathan Bennett, Kants Analytic (Cambridge: Cambridge University Press, 1966), p. viii. Afterword 303 That Plato fails to embody philosophical perfection is not a reason to give up on him or on ourselves. Some Suggestions for Further Reading Readers intrigued by Platos thought will want to read Rebecca Goldstein, Plato at the Googleplex: Why Philosophy Will Not Go Away (New York: Vintage, 2015), a brilliant, wise, and funny book which imagines Plato on a contemporary book tour. Readers interested in a brief, compelling account of the life of Socrates by an eminent biographer should see Paul Johnson, Socrates: A Man for Our Times (New York: Penguin Books, 2011). Readers interested in exploring more of Platos philosophical thought will find it all here: Plato: Complete Works, ed. by John Cooper (Indianapolis: Hackett Publishing, 1997). For a canonical philosopher whose thinking is very much at odds with Platos, interested readers might try both David Hume, An Enquiry Concerning Human Understanding (Indianapolis: Hackett Publishing, 1993) and Hume, An Enquiry Concerning the Principles of Morals (Indianapolis: Hackett Publishing, 1983). List of Illustrations Introduction Attic Greek Black-figure Neck Amphora attributed to the Princeton Painter, ca. 550540 BCE. Photograph by Aisha Abdel (2018), Wikimedia, Pulic Domain, https://commons.wikimedia.org/wiki/ File:Terracotta_neck-amphora_of_Panathenaic_shape_(jar)_MET_ DP161828_white_balanced_white_bg.png xii Chapter 1 Theodoor van Thulden, Telemachus and Ulysses Meet in Eumaeus Hut. Photograph by Mr. Nostalgic (2019), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/File:Odysseus_en_ Telemachus_in_de_hut_van_Eumaeus_De_werken_van_Odysseus_ (serietitel),_RP-P-OB-66.764.jpg xxviii Chapter 2 Greek vase, ca. 550 BCE. Photograph by Materia Viva (2010), Wikimedia, CC BY-SA 4.0, https://commons.wikimedia.org/wiki/ Category:Mus%C3%A9e_Saint-Raymond,_26172#/media/File:MSR26172-MV-R-b.jpg 24 306 Platos Republic: An Introduction Chapter 3 Franz Caucig, Socrates with a Disciple and Diotima (1810). Photograph by Sporti (2014), Wikimedia, Public Domain, https://commons. wikimedia.org/wiki/File:Franc_Kav%C4%8Di%C4%8D_-_ Sokrat_z_u%C4%8Dencem_in_Diotimo.jpg#/media/File:Franc_ Kavi_-_Sokrat_z_uencem_in_Diotimo.jpg 54 Chapter 4 Figure of a boy writing on a kylix, 480 B.C. Photograph by Reame (2019), Wikimedia, CC BY-SA 4.0, https://commons.wikimedia. org/wiki/File:Figura_ragazzo_che_scrive_su_kylix.jpg#/media/ File:Figura_ragazzo_che_scrive_su_kylix.jpg 74 Chapter 5 Josef Abel, Socrates Teaching his Disciples (1807). Photograph by Jarash (2015), Wikimedia, Public Domain, https://commons. wikimedia.org/wiki/File:Josef_Abel_1807_Socrates_teaching_his_ disciples.jpg 92 Chapter 6 Bust of Athena, of the Velletri Pallas type. Copy of the 2nd century CE after a votive statue of Kresilas in Athens (ca. 430420 BCE). Photograph by Aavindraa (2010), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/Category:Athena#/media/ File:Bust_Athena_Velletri_Glyptothek_Munich_213.jpg 112 Chapter 7 Ernst Herter, Amazonenkampf (1891). Photograph by Mutter Erde (2017), Wikimedia, Public Domain, https://upload. wikimedia.org/wikipedia/commons/6/65/Ernst_Herter_-_ Amazonenkampf%2C_c._1891.jpg 130 List of Illustrations 307 Chapter 8 John La Farge, The Relation of the Individual to the State: Socrates and His Friends Discuss The Republic, as in Platos Account, color study for mural (1903). Photograph by Pharos (2017), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/ File:The_Relation_of_the_Individual_to_the_State-_Socrates_and_ His_Friends_Discuss_%22The_Republic,%22_as_in_Plato%27s_ Account;_Color_Study_for_Mural,_Supreme_Court_Room,_Saint_ Paul,_Minnesota_State_Capitol,_Saint_Paul_MET_187194.jpg 150 Chapter 9 B-side of bell krater with scene of three young men with himatia in an arena. Photograph by ngel M. Felicsimo (2016), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/ File:Cr%C3%A1tera_(38877852382).jpg 174 Chapter 10 Achilles and Ajax playing a board game overseen by Athena (c. 510 BCE). Photograph by Aisha Abdel (2018), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/Category:Blackfigure_pottery#/media/File:Attic_Black-Figure_Neck_Amphora_-_ Achilles_and_Ajax_playing_a_board_game_overseen_by_Athena.jpg Fig. 1 The Visible World and the Intelligible World 190 Fig. 2 The Visible World (a and b) and the Intelligible World (c and d) 198 Fig. 3 The Visible World and the Intelligible World: Belief and Knowledge 199 197 Chapter 11 Markus Maurer, drawing of Platos Allegory of the Cave with Wikipedias logo as the sun (2015). Photograph by Crystallizedcarbon (2015), Wikimedia, CC BY-SA 3.0, https:// commons.wikimedia.org/wiki/File:Plato_Cave_Wikipedia.gif#/ media/File:Plato_Cave_Wikipedia.gif 210 308 Platos Republic: An Introduction Chapter 12 M. A. Barth, Return of Peisistratus to Athens with the false Minerva (1838). Photograph by Patna (2018), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/File:Return_of_Peisistratus_ to_Athens_with_the_false_Minerva.jpg#/media/File:Return_of_ Peisistratus_to_Athens_with_the_false_Minerva.jpg 228 Chapter 13 Unidentified artist, Image satirique du tennis chez les Anciens, La revue athltique, 3 (1890), 169. Photograph by Skblzz1 (2018), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/ File:Image_satirique_du_tennis_chez_les_Anciens_(1890).jpg 250 Fig. 4 Mller-Lyer illusion. Photograph by Fibonacci (2007), Wikimedia, CC BY-SA 3.0, https://commons.wikimedia. org/w/index.php?curid=1792612) 261 Fig. 5 Mller-Lyer illusion. Photograph by Fibonacci (2007), Wikimedia, CC BY-SA 3.0, https://commons.wikimedia. org/w/index.php?curid=1792612) 250 Chapter 14 Muse tuning two kitharai. Detail of the interior from an Attic white-ground cup (c. 470460 BCE). Photograph by Jastrow (2006), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/ File:Muse_lyre_Louvre_CA482.jpg#/media/File:Muse_lyre_Louvre_ CA482.jpg 274 Afterword Head of Platon, Roman copy. Photograph by Bibi Saint-Pol (2007), Wikimedia, Public Domain, https://commons.wikimedia.org/wiki/ File:Head_Platon_Glyptothek_Munich_548.jpg#/media/File:Head_ Platon_Glyptothek_Munich_548.jpg 298 Bibliography Barnes, Jonathan, ed., The Complete Works of Aristotle (Revised Oxford Translation), 2 vols (Princeton: Princeton University Press, 1984), https://doi. org/10.1515/9781400835843 (vol. 1), https://doi.org/10.1515/9781400835850 (vol. 2). Bennett, Jonathan, Kants Analytic (Cambridge: Cambridge University Press, 1966), https://doi.org/10.1017/cbo9781316492901 Berlin, Isaiah, Two Concepts of Liberty in Berlin, Liberty: Four Essays on Liberty, ed. by Henry Hardy (New York: Oxford University Press, 2002), https://doi. org/10.1093/019924989x.001.0001 Bhagavad Gita, trans. by Eknath Easwaran, 2nd ed. (Tomales, CA: Nilgiri Press, 2007). Burnyeat, Myles, Culture and Society in Platos Republic, in The Tanner Lectures on Human Values, vol. 20 (Salt Lake City: University of Utah Press, 1999). Camus, Albert, The Myth of Sisyphus, trans. by Justin OBrien (New York: Vintage International, 2018). Coetzee, J. M., Elizabeth Costello (New York: Viking, 2003). David Hume: A Treatise on Human Nature, ed. by L. A. Selby-Bigge, 2nd ed., rev. by P. H. Nidditch (Oxford: Clarendon Press, 1987). Demos, Raphael, A Fallacy in Platos Republic?, Philosophical Review, 73 (1964), 39598, https://doi.org/10.2307/2183665 Dickens, Charles, Hard Times (London: Penguin Books, 1994). Emerson, Ralph Waldo, Essays (New York: Harper Perennial, 1995). Epicurus: The Art of Happiness, trans. by George Strodach (New York: Penguin Books, 2012). Fitzgerald, F. Scott, The Crack-Up (New York: New Directions Publishing, 2009). 310 Platos Republic: An Introduction Frederick Douglass: Autobiographies: Narrative of the Life of Frederick Douglass, an American Slave/ My Bondage and My Freedom/ Life and Times of Frederick Douglass, ed. by Henry Louis Gates (New York: Library of America, 1994). Johnson, Paul, Socrates: A Man for Our Times (New York: Penguin Books, 2011). Kant: Groundwork of the Metaphysics of Morals, trans. and ed. by Mary K. Gregor (New York: Cambridge University Press, 1998), https://doi.org/10.1017/ CBO9780511809590 McCarthy, Cormac, No Country for Old Men (New York: Vintage Books, 2006). McEwan, Ian, Enduring Love (New York: Anchor Books, 1998). Mill, John Stuart, On Liberty, ed. by Elizabeth Rappaport (Indianapolis: Hackett Publishing, 1978 [orig. pub. 1859]). Murphy, Jeffrie, Forgiveness and Resentment in Jeffrie Murphy and Jean Hampton, Forgiveness and Mercy (New York: Cambridge University Press, 1988). https://doi.org/10.1017/cbo9780511625121.003 Nails, Debra, The Dramatic Date of Platos Republic, The Classical Journal, 93.4 (1998), 38396. Nussbaum, Martha, The Fragility of Goodness: Luck and Ethics in Greek Tragedy and Philosophy (Cambridge, University of Cambridge Press, 1986). Nyhan, Brendan and Jason Reifler, When Corrections Fail: The Persistence of political Misperceptions, Political Behavior, 32 (2010), 30330. https://doi. org/10.1007/s1110901091122 Plato: Five Dialogues: Euthyphro, Apology, Crito, Meno, Phaedo, trans. by G. M. A. Grube (Indianapolis: Hackett Publishing, 1981). Plato: Republic, trans. by G. M. A. Grube, rev. by C. D. C. Reeve (Indianapolis: Hackett Publishing, 1992). Plato: Theaetetus, tr. by M. J. Levett, rev. by Myles Burnyeat, ed. by Bernard Williams (Indianapolis: Hackett Publishing, 1992). Rosch, Eleanor, Natural categories, Cognitive Psychology, 4 (1973), 32850. https://doi.org/10.1016/00100285(73)900170 Russell, Bertrand, Introduction to Mathematical Philosophy (New York: MacMillan, 1919). Sachs, David, A Fallacy in Platos Republic, Philosophical Review, 72 (1963), 141 58. https://doi.org/10.2307/2183101 Schiller, Friedrich, On the Aesthetic Education of Man, trans. by Keith Tribe, ed. by Alexander Schmidt (New York: Penguin Books, 2016 [orig. pub. 1795]). Thomas, Laurence, Friendship and Other Loves, Synthese, 72.2 (1987), 21736. Thompson, Hunter S., The Great Shark Hunt: Strange Tales from a Strange Time (New York: Simon & Schuster, 1979). Bibliography 311 Thomson, Judith Jarvis, A Defense of Abortion, Philosophy & Public Affairs, 1 (1971), 4766. Williams, Bernard, Ethics and the Limits of Philosophy (Cambridge: Harvard University Press, 1986). Wittgenstein, Ludwig, Philosophical Investigations, 3rd ed., trans. by G. E. M. Anscombe (Oxford: Basil Blackwell, 1973). Wood, Gordon S., Empire of Liberty: A History of the Early Republic, 17891815 (New York: Oxford University Press, 2011). Zhuangzi: The Complete Writings, trans. by Brook Ziporyn (Indianapolis: Hackett Publishing, 2020). Index aesthetic judgment and moral judgment 80, 95, 116 Aristotle xiv, xv, 3, 10, 19, 21, 26, 29, 39, 48, 61, 72, 81, 97, 100, 102, 123, 152, 179, 181, 189, 233, 241, 253, 271, 285287, 294295, 311 belief. See also knowledge distinctive of non-philosophers xxiv, 153154, 161162, 176 particulars are the objects of belief 161, 163164, 168, 197, 203 Cave Allegory. See Chapter 11 Confucius 106 courage 118 courage as a personal virtue 17, 7879, 98, 109111, 120, 180, 294 courage as a political virtue 101102, 118, 120, 153 dialectic 75, 120, 184, 195, 202, 204, 206208, 214, 218, 235 disability xxii, 8485, 90, 98 disgust 67, 81, 115117, 123, 127, 136137, 245, 283 distaste. See disgust divided line analogy xviii, xxiv, 196, 198202, 211217, 219, 287, 301 education (paideia) xiv, xviii, xxii, xxv, 4, 66, 72, 9496, 102, 110111, 116, 118, 120, 122, 133134, 136137, 139, 147, 166, 176, 178, 207, 211212, 214, 222, 224, 278, See Chapter 4 in decaying cities and souls 230232, 235, 244245 point of the Cave Allegory 211 Epicurus 239241, 246, 267 epistemology epistemological argument against imitative poetry 279, 283 relation to metaphysics 153, 161, 199, 279 falsehood 176177 noble falsehood, the xxii, 8790, 105106, 110, 134, 285, 292 true v. verbal falsehoods 7678, 8890, 102, 133, 145, 177, 285 feminism xxiii, 140144, 148, 241 Form of the good, the and wisdom 186, 191, 268 epistemological, metaphysical, moral foundation xxiv, 156, 191, 195196, 204205 role in dialectic 204205 role in education (paideia) 211, 214 sun analogy 194196 Forms, the Forms as essences xxiv, 154156, 158161, 178, 195, 203, 214, 264, 277 located in the intelligible world xxiv, xxv, 156, 195198, 200, 211, 217218, 301 mind-independent reality of xxiv, 10, 154, 156157, 159160, 175, 218, 263 314 Platos Republic: An Introduction more real than particular objects xxv, 10, 156157, 160, 191, 197, 212, 217, 258, 263 particular objects as instances of xxiv, 154157, 160163, 171, 196 Powers Argument, the xxiv, xxv, 161168, 172, 175, 183, 196, 217218, 264265, 301 function. See virtue(s) Gyges, ring of 6364, 123, 245 happiness (eudaimonia) xvi, xix, 3940, 4749, 66, 9394, 146, 152, 219, 225, 236, 240, 252254, 270, 301 arguments that a just life is happier 4849, 51, See Chapter 13 hedonism 192193, 239, 254 Hume, David 4546, 126127, 234, 267, 303, 311 hypotheses xxiv, 120, 184, 200202, 204206, 217 Socrates hypothetical method 195, 206, 218 ideal city (polis) cooperative, not competitive 68 decline of the ideal city and soul xxv, See Chapter 12 economic organization via the Specialization Principle 69, 72, 84, 106, 126, 137138, 235236, 290 first, rustic city 68, 71, 97, 238, 276 second, luxurious city 71, 238 illusions optical and hedonic 261263 justice as moral virtue generally xv, xxi, 1, 7 conventionalism about 31, 41, 6163 defined as benefiting friends and harming enemies 1116, 1920, 48, 182 defined as each class of the city doing its own work 106, 121 defined as each part of the soul doing its own work xxiii, 121 defined as paying ones debts and telling the truth xxi, 78 defined as what benefits the powerful xxi, 2528, 3032, 35, 38 immoralism about 42, 45, 47, 4950 in decaying cities and souls 235 injustice worsens but does not destroy the soul 291 intrapersonal being v. interpersonal doing 93, 121 justice as a meta-virtue 109 justice as a personal virtue xvii, xix, xxii, xxiii, 9394, 107, 118, 183 justice as a political virtue xvii, xix, xxii, 9394, 106, 113 justice in decaying cities and souls 232, 234236, 242, 245246 personal justice as psychic health 123 relation to happiness xv, xvi, xix, xxii, 3839, 4647, 50, 56, 94, 265, 268 reputational benefits of seeming just 6567, 234235, 252 search for real definition of xiv, xv, xvii, xx, xxi, xxii, 2, 7, 26, 45, 50, 93 search for the real definition of 7, 96, 229 Kant, Immanuel 10, 8081, 122, 226, 266, 300, 302 knowledge xiv, xxiv, 80, 87, 100, 118, 125, 139, 164, 179, 203, 252, 268, 270 as justified true belief 5556, 66, 101, 167, 169, 204 as the good 193194 distinctive of philosophers xxiv, 153154, 176 infallibility of 168172 Index knowledge v. belief xxiv, 101, 153154, 161163, 166169, 172, 175176, 196197, 203, 217, 264 the Forms are the objects of knowledge 154, 161164, 169, 171, 186, 196197 love 8283, 8788, 125126, 147, 153, 176179, 245, 253 metaphysics Forms, the. See Forms, the Metaphysics of Pleasure Argument, the xxv, 257, 259, 263265, 301302 Platos metaphysical elevator 151, 157, 161, 191, 196, 204, 217218, 263 Platos two-worlds metaphysics 172, 197, 217218, 264, 287, 301 moderation moderation as a personal virtue 78, 80, 114, 119, 179, 181, 275 moderation as a political virtue xxii, 102104, 109, 118 poetry constraints on poetic content 7678, 275 constraints on poetic style 7980, 275, 282 epistemological argument against imitative poetry 279281 harmonic mode and rhythm 7981, 95, 275, 282 imitation and narration 79, 276277, 282283 metaphysical argument against imitative poetry 277279 moral argument against imitative poetry 282284 Powers Argument, the. See Forms, the soul (psuch) a fourth part of the soul? 287289 315 analogy to city (polis) xxii, 67, 73, 93, 97, 114, 118, 121, 144, 183, 229, 289 an image of the soul in words 120, 265, 267268 appetitive part xxiii, 115, 143 aristocratic soul governed by reason 256 democratic soul governed by lawful unnecessary appetites 238 distinctive pleasures of the souls distinct parts 254, 258 division via the Opposition Principle 114115, 206 education as turning the soul 211212, 214 harmony and justice 124 immortality of 48, 289292, 296 myth of the metals, the 8889, 110, 141 oligarchic soul governed by necessary appetites 233, 235 rational part xxiii, 115 spirited part xxiii, 115117 timocratic soul governed by spirit 232 tyrannical soul governed by lawless unnecessary appetites 244 virtue(s) cardinal virtues xxii, 17, 9798, 105, 108, 111, 153, 181, 242 function 1719, 37, 42, 4849, 69, 94, 100101, 117, 154, 162, 164, 166, 179 holistic v. particular virtues 100102, 104, 110 personal virtues xxiii, 103, 118, 119, 120. See also courage; justice; moderation; wisdom political virtues xxii, xxiii, 96. See also courage; justice; moderation; wisdom virtue ethics 39, 122 virtues v. crafts, skills xxi, 1315, 17, 35, 3738, 4345, 47, 168 316 Platos Republic: An Introduction wisdom knowledge of what is best for the whole 87, 100101, 109, 124, 138, 175, 180, 186, 191192, 219, 236, 270 wisdom as a personal virtue 118, 124, 126, 138 wisdom as a political virtue 100101 About the Team Alessandra Tosi was the managing editor for this book. Melissa Pukiss performed the copy-editing and proofreading. Anna Gatti designed the cover using InDesign. The cover was produced in InDesign using Fontin (titles) and Calibri (text body) fonts. Melissa Purkiss typeset the book in InDesign and produced the paperback and hardback editions. The text font is Tex Gyre Pagella; the heading font is Californian FB. Luca Baffa produced the EPUB, MOBI, PDF, HTML, and XML editions the conversion is performed with open source software freely available on our GitHub page (https://github.com/OpenBookPublishers). This book need not end here Share All our books including the one you have just read are free to access online so that students, researchers and members of the public who cant afford a printed edition will have access to the same ideas. This title will be accessed online by hundreds of readers each month across the globe: why not share the link so that someone you know is one of them? This book and additional content is available at: https://doi.org/10.11647/OBP.0229 Customise Personalise your copy of this book or design new books using OBP and thirdparty material. Take chapters or whole books from our published list and make a special edition, a new anthology or an illuminating coursepack. Each customised edition will be produced as a paperback and a downloadable PDF. Find out more at: https://www.openbookpublishers.com/section/59/1 Like Open Book Publishers Follow @OpenBookPublish Read more at the Open Book Publishers You may also be interested in: Metaethics from a First Person Standpoint: An Introduction to Moral Philosophy Catherine Wilson https://doi.org/10.11647/OBP.0087 Wellbeing, Freedom and Social Justice: The Capability Approach Re-Examined Ingrid Robeyns https://doi.org/10.11647/OBP.0130 Ovid, Metamorphoses, 3.511-733. Ingo Gildenhard and Andrew Zissos https://doi.org/10.11647/OBP.0073 Platos Republic An Introduction SEAN MCALEER This book is a lucid and accessible companion to Platos Republic, throwing light upon the texts arguments and main themes, placing them in the wider context of the texts structure. In its illuminaon of the philosophical ideas underpinning the work, it provides readers with an understanding and appreciaon of the complexity and literary arstry of Platos Republic. McAleer not only unpacks the key overarching quesons of the text What is justice? And Is a just life happier than an unjust life? but also highlights some fascinang, overlooked passages which contribute to our understanding of Platos philosophical thought. Platos Republic: An Introduction oers a rigorous and thought-provoking analysis of the text, helping readers navigate one of the worlds most inuenal works of philosophy and polical theory. With its approachable tone and clear presentaon, it constutes a welcome contribuon to the eld, and will be an indispensable resource for philosophy students and teachers, as well as general readers new to, or returning to, the text. As with all Open Book publicaons, this enre book is available to read for free on the publishers website. Printed and digital edions, together with supplementary digital material, can also be found at www.openbookpublishers.com Cover image: Anselm Feuerbachs The Symposium (1871-1874). Cover design by Anna Ga. ebook ebook and OA edions also available ...
- Créateur:
- McAleer, Sean
- La description:
- This book is a lucid and accessible companion to Plato’s Republic, throwing light upon the text’s arguments and main themes, placing them in the wider context of the text’s structure. In its illumination of the philosophical...
- Type:
- Text
- Type de ressource d'apprentissage:
- Textbook
- iveau d'éducation:
- College / Upper division
- Public:
- Student
-
- Correspondances de mots clés:
- ... Think Raku How to Think Like a Computer Scientist 2nd Edition, Version 0.6 January 2020 Think Raku How to Think Like a Computer Scientist 2nd Edition, Version 0.6 January 2020 Laurent Rosenfeld, with Allen B. Downey Green Tea Press Needham, Massachusetts Copyright 2017-2020 Allen Downey, Laurent Rosenfeld. Green Tea Press 9 Washburn Ave Needham MA 02492 Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-NonCommercial 3.0 Unported License, which is available at http: //creativecommons.org/licenses/by-nc/3.0/. The original form of this book is LATEX source code. Compiling this LATEX source has the effect of generating a device-independent representation of a textbook, which can be converted to other formats and printed. The LATEX source for this book is available from https://github.com/LaurentRosenfeld/think_ raku/ Preface Welcome to the art of computer programming and to the new Raku language. This is one of the first books using Raku, a powerful, expressive, malleable and highly extensible programming language. But this book is less about Raku, and more about learning how to write programs for computers. This book is intended for beginners and does not require any prior programming knowledge, but it is my hope that even those of you with programming experience will benefit from reading it. The Aim of this Book This aim of this book is not primarily to teach Raku, but instead to teach the art of programming, using the Raku language. After having completed this book, you should hopefully be able to write programs to solve relatively difficult problems in Raku, but my main aim is to teach computer science, software programming, and problem solving rather than solely to teach the Raku language itself. This means that I will not cover every aspect of Raku, but only a (relatively large, but yet incomplete) subset of it. By no means is this book intended to be a reference on the language. It is not possible to learn programming or to learn a new programming language by just reading a book; practicing is essential. This book contains a lot of exercises. You are strongly encouraged to make a real effort to do them. And, whether successful or not in solving the exercises, you should take a look at the solutions in the Appendix, as, very often, several solutions are suggested with further discussion on the subject and the issues involved. Sometimes, the solution section of the Appendix also introduces examples of topics that will be covered in the next chapterand sometimes even things that are not covered elsewhere in the book. So, to get the most out the book, I suggest you try to solve the exercises as well as review the solutions and attempt them. There are more than one thousand code examples in this book; study them, make sure to understand them, and run them. When possible, try to change them and see what happens. Youre likely to learn a lot from this process. The History of this Book There is a simple thing that you need to know in order to understand the coming paragraphs. The Raku programming language has not always been called Raku. The project vi Chapter 0. Preface started under the Perl 6 name, because it was originally thought to be the next version of Perl, a successor to Perl 5. With time, however, the language has grown to be syntactically quite different from Perl, although keeping the spirit of Perl and carrying forward the ideals of the Perl Community. Because of these differences, it was decided in October 2019 to rename the Perl 6 language into Raku. The book that you are reading was originally called Think Perl 6. This new edition thus reflects the re-branding of the language. In the course of the three to four years before the beginning of 2016, I had translated or adapted to French a number of tutorials and articles on what was still called at the time Perl 6, and Id also written a few entirely new ones in French. 1 Together, these documents represented by the end of 2015 somewhere between 250 and 300 pages of material on Perl 6. By that time, I had probably made public more material on this new language in French than all other authors taken together. In late 2015, I began to feel that a Perl 6 document for beginners was something missing that I was willing to undertake. I looked around and found that it did not seem to exist in English either. I came to the idea that, after all, it might be more useful to write such a document initially in English, to give it a broader audience. I started contemplating writing a beginner introduction to Perl 6 programming. My idea at the time was something like a 50- to 70-page tutorial and I started to gather material and ideas in this direction. Then, something happened that changed my plans. In December 2015, friends of mine were contemplating translating into French Allen B. Downeys Think Python, Second Edition2 . I had read an earlier edition of that excellent book and fully supported the idea of translating it3 . As it turned out, I ended up being a cotranslator and the technical editor of the French translation of that book4 . While working on the French translation of Allens Python book, the idea came to me that, rather than writing a tutorial on Perl 6, it might be more useful to make a Perl 6 translation of Think Python. Since I was in contact with Allen in the context of the French translation, I suggested this to Allen, who warmly welcomed the idea. This is how I started to write this book late January 2016, just after having completed the work on the French translation of his Python book. I had to use the Perl 6 name in the preceding paragraphs, since it is the way it was named at that point in history. From now on, Ill use the new name of the language, Raku, unless referring to events prior to the renaming. This book is thus largely derived on Allens Think Python, but adapted to Raku. As it happened, it is also much more than just a Raku translation of Allens book: with quite a lot of new material, it has become a brand new book, largely indebted to Allens book, but yet a new book for which I take all responsibility. Any errors are mine, not Allens. My hope is that this will be useful to the Raku community, and more broadly to the open source and general computer programming communities. In an interview with LinuxVoice (July 2015), Larry Wall, the creator of Raku, said: We do think that Perl 6 will be learnable as a first language. Hopefully this book will contribute to making this happen. 1 See 2 See for example http://perl.developpez.com/cours/#TutorielsPerl6. http://greenteapress.com/wp/think-python-2e/. 3 I know, its about Python, not Perl or Raku. But I dont believe in engaging in language wars and think that we all have to learn from other languages; to me, Perls motto, there is more than one way to do it, also means that doing it in Python (or some other language) is truly an acceptable possibility. 4 See http://allen-downey.developpez.com/livres/python/pensez-python/. vii Acknowledgments I just dont know how I could thank Larry Wall to the level of gratitude that he deserves for having created Perl in the first place, and Raku more recently. Be blessed for eternity, Larry, for all of that. And thank to you all of you who took part to this adventure (in no particular order), Tom, Damian, chromatic, Nathan, brian, Jan, Jarkko, John, Johan, Randall, Mark Jason, Ovid, Nick, Tim, Andy, Chip, Matt, Michael, Tatsuhiko, Dave, Rafael, Chris, Stevan, Saraty, Malcolm, Graham, Leon, Ricardo, Gurusamy, Scott and too many others to name. All my thanks also to those who believed in this Perl 6 and then Raku project and made it happen, including those who quit at one point or another but contributed for some time; I know that this wasnt always easy. Many thanks to Allen Downey, who very kindly supported my idea of adapting his book to this language and helped me in many respects, but also refrained from interfering in what I was putting into this new book. I very warmly thank the people at OReilly who accepted the idea of this book and suggested many corrections or improvements. I want to thank especially Dawn Schanafelt, my editor at OReilly, whose advice has truly contributed to making this a better book. Many thanks also to Charles Roumeliotis, the copy editor, and Kristen Brown, the production editor, who fixed many typographical problems and spelling mistakes. Thanks a lot to readers who have offered comments or submitted suggestions or corrections, as well as encouragements. If you see anything that needs to be corrected or that could be improved, please kindly send your comments to think.perl6(at)gmail.com. Contributor List I would like to thank especially Moritz Lenz and Elizabeth Mattijsen, who reviewed in detail drafts of this book and suggested quite a number of improvements and corrections. Liz spent a lot of time on a detailed review of the full content of this book and I am especially grateful to her for her numerous and very useful comments. Thanks also to Timo Paulssen and ryanschoppe who also reviewed early drafts and provided some useful suggestions. Many thanks also to Uri Guttman, who reviewed this book and suggested a number of small corrections and improvements shortly before publication. Kamimura, James Lenz, and Jeff McClelland each submitted a couple of corrections in the errata list on the OReilly web site. zengargoyle pointed out a spurious character in a regex and fixed it in the GitHub repository of the book. zengargoyle also suggested a clarification in the chapter about functional programming. Another James (second name unknown to me) submitted an erratum on the OReilly web site. Mikhail Korenev suggested accurate corrections to three code samples. Sbastien Dorey, Jean Forget, and Roland Schmitz sent some e-mails suggesting a few useful corrections or improvements. Luis F. Uceta translated this book into Spanish and found in the process quite a few typos he corrected on the Github repository. Gil Magno, zoffixznet and Joaquin Ferrero also suggested some corrections on Github. Threadless-screw fixed a couple of faulty cross-references in the chapter about hashes. Boyd Duffee spotted two code samples that used to work fine when I wrote them four years ago, but no longer work, due to some implementation changes. leszekdubiel suggested an improvement that probably clarifies a bit the meaning of a sentence. viii Chapter 0. Preface Contents Preface v I Starting with the Basics 1 1 The Way of the Program 5 1.1 What is a Program? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.2 Running Raku . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.3 The First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.4 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.5 Values and Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.6 Formal and Natural Languages . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.7 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.8 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2 Variables, Expressions and Statements 15 2.1 Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.2 Variable Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.3 Expressions and Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.4 Script Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 2.5 One-Liner Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 2.6 Order of Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 2.7 String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.8 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 2.9 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 2.10 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 x 3 4 Contents Functions 27 3.1 Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 3.2 Functions and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 3.3 Math functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 3.4 Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.5 Adding New Functions (a.k.a. Subroutines) . . . . . . . . . . . . . . . . . . 32 3.6 Definitions and Uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 3.7 Flow of Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 3.8 Parameters and Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 3.9 Variables and Parameters Are Local . . . . . . . . . . . . . . . . . . . . . . 37 3.10 Stack Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 3.11 Fruitful Functions and Void Functions . . . . . . . . . . . . . . . . . . . . . 38 3.12 Function Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 3.13 Immutable and Mutable Parameters . . . . . . . . . . . . . . . . . . . . . . 41 3.14 Functions and Subroutines as First-Class Citizens . . . . . . . . . . . . . . 42 3.15 Why Functions and Subroutines? . . . . . . . . . . . . . . . . . . . . . . . . 44 3.16 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 3.17 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 3.18 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Loops, Conditionals, and Recursion 49 4.1 Integer Division and Modulo . . . . . . . . . . . . . . . . . . . . . . . . . . 49 4.2 Boolean Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 4.3 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.4 Conditional Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 4.5 Alternative Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 4.6 Chained Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 4.7 Nested Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 4.8 If Conditionals as Statement Modifiers . . . . . . . . . . . . . . . . . . . . . 56 4.9 Unless Conditional Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.10 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.11 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Contents 5 6 xi 4.12 Stack Diagrams for Recursive Subroutines . . . . . . . . . . . . . . . . . . . 61 4.13 Infinite Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 4.14 Keyboard Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 4.15 Program Arguments and the MAIN Subroutine . . . . . . . . . . . . . . . . 62 4.16 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 4.17 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 4.18 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Fruitful Subroutines 69 5.1 Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5.2 Incremental Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 5.3 Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 5.4 Boolean Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 5.5 A Complete Programming Language . . . . . . . . . . . . . . . . . . . . . . 75 5.6 More Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 5.7 Leap of Faith . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 5.8 One More Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 5.9 Checking Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 5.10 Multi Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 5.11 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 5.12 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 5.13 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Iteration 85 6.1 Assignment Versus Equality . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 6.2 Reassignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 6.3 Updating Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 6.4 The while Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 6.5 Local Variables and Variable Scoping . . . . . . . . . . . . . . . . . . . . . . 89 6.6 Control Flow Statements (last, next, etc.) . . . . . . . . . . . . . . . . . . . 91 6.7 Square Roots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 6.8 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 6.9 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 6.10 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 6.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 xii 7 Contents Strings 99 7.1 A String is a Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 7.2 Common String Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 7.2.1 String Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 7.2.2 Searching For a Substring Within the String . . . . . . . . . . . . . . . 100 7.2.3 Extracting a Substring from a String . . . . . . . . . . . . . . . . . . . 101 7.2.4 A Few Other Useful String Functions or Methods . . . . . . . . . . . 102 7.3 String Traversal With a while or for Loop . . . . . . . . . . . . . . . . . . . 104 7.4 Looping and Counting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.5 Regular Expressions (Regexes) . . . . . . . . . . . . . . . . . . . . . . . . . 106 7.6 Using Regexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 7.7 Building your Regex Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . 109 7.8 7.9 106 7.7.1 Literal Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 7.7.2 Wildcards and Character Classes . . . . . . . . . . . . . . . . . . . . . 109 7.7.3 Quantifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 7.7.4 Anchors and Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . 111 7.7.5 Alternation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 7.7.6 Grouping and Capturing . . . . . . . . . . . . . . . . . . . . . . . . . 114 7.7.7 Adverbs (a.k.a. Modifiers) . . . . . . . . . . . . . . . . . . . . . . . . . 114 7.7.8 Exercises on Regexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Putting It All Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 7.8.1 Extracting Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 7.8.2 Extracting an IP Address . . . . . . . . . . . . . . . . . . . . . . . . . 117 Substitutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 7.9.1 The subst Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 7.9.2 The s/search/replace/ Construct . . . . . . . . . . . . . . . . . . . . 119 7.9.3 Using Captures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 7.9.4 Adverbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 7.10 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 7.11 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 7.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Contents xiii 8 Case Study: Word Play 127 8.1 Reading from and Writing to Files . . . . . . . . . . . . . . . . . . . . . . . 127 8.2 Reading Word Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 8.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 8.4 Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 9 8.4.1 Words Longer Than 20 Characters (Solution) . . . . . . . . . . . . . . 130 8.4.2 Words with No e (Solution) . . . . . . . . . . . . . . . . . . . . . . . 8.4.3 Avoiding Other Letters (Solution) . . . . . . . . . . . . . . . . . . . . 132 8.4.4 Using Only Some Letters (Solution) . . . . . . . . . . . . . . . . . . . 133 8.4.5 Using All Letters of a List (Solution) . . . . . . . . . . . . . . . . . . . 134 8.4.6 Alphabetic Order (Solution) . . . . . . . . . . . . . . . . . . . . . . . . 8.4.7 Another Example of Reduction to a Previously Solved Problem . . . 135 131 134 8.5 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 8.6 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 8.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 Arrays and Lists 139 9.1 Lists and Arrays Are Sequences . . . . . . . . . . . . . . . . . . . . . . . . . 139 9.2 Arrays Are Mutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.3 Adding New Elements to an Array or Removing Some . . . . . . . . . . . 143 9.4 Stacks and Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 9.5 Other Ways to Modify an Array . . . . . . . . . . . . . . . . . . . . . . . . . 146 9.6 Traversing a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 9.7 New Looping Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 9.8 Map, Filter and Reduce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 141 9.8.1 Reducing a List to a Value . . . . . . . . . . . . . . . . . . . . . . . . . 151 9.8.2 The Reduction Metaoperator . . . . . . . . . . . . . . . . . . . . . . . 152 9.8.3 Mapping a List to Another List . . . . . . . . . . . . . . . . . . . . . . 152 9.8.4 Filtering the Elements of a List . . . . . . . . . . . . . . . . . . . . . . 153 9.8.5 Higher Order Functions and Functional Programming . . . . . . . . 154 9.9 Fixed-Size, Typed and Shaped Arrays . . . . . . . . . . . . . . . . . . . . . 155 9.10 Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 xiv Contents 9.11 Sorting Arrays or Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 9.12 More Advanced Sorting Techniques . . . . . . . . . . . . . . . . . . . . . . 158 9.13 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 9.14 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 9.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 10 Hashes 165 10.1 A Hash is a Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 10.2 Common Operations on Hashes . . . . . . . . . . . . . . . . . . . . . . . . . 168 10.3 Hash as a Collection of Counters . . . . . . . . . . . . . . . . . . . . . . . . 169 10.4 Looping and Hashes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 10.5 Reverse Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 10.6 Testing for Existence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 10.7 Hash Keys Are Unique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 10.8 Hashes and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 10.9 Memos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 10.10 Hashes as Dispatch Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 10.11 Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 10.12 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 10.13 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 10.14 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 11 Case Study: Data Structure Selection 183 11.1 The Ternary Conditional Operator . . . . . . . . . . . . . . . . . . . . . . . 183 11.2 The given ... 11.3 Multiple Conditionals with Junctions . . . . . . . . . . . . . . . . . . . . . . 185 11.4 Subroutine Named and Optional Parameters . . . . . . . . . . . . . . . . . 187 when Switch Statement . . . . . . . . . . . . . . . . . . . 184 11.4.1 Named Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 11.4.2 Optional Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 11.5 Word Frequency Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 11.6 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 11.7 Word Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 Contents xv 11.8 Most Common Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 11.9 Optional Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 11.10 Hash Subtraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 11.11 Constructing New Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 195 11.12 Sets, Bags and Mixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 11.13 Random Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 11.14 Markov Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 11.15 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 11.16 Building Your Own Data Structures . . . . . . . . . . . . . . . . . . . . . . 201 II 11.16.1 Linked Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 11.16.2 Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 11.16.3 Binary Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 11.17 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 11.18 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 11.19 Exercises: Huffman Coding . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 11.19.1 Variable-Length Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 11.19.2 The Frequency Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 11.19.3 Building the Huffman Code . . . . . . . . . . . . . . . . . . . . . . . . 210 Moving Forward 12 Classes and Objects 213 217 12.1 Objects, Methods and Object-Oriented Programming . . . . . . . . . . . . 217 12.2 Programmer-Defined Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 12.3 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 12.4 Creating Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 12.5 Rectangles and Object Composition . . . . . . . . . . . . . . . . . . . . . . 224 12.6 Instances as Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 12.7 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 12.7.1 The Pixel Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 12.7.2 The MovablePoint Class . . . . . . . . . . . . . . . . . . . . . . . . . . 229 12.7.3 Multiple Inheritance: Attractive, but Is It Wise? . . . . . . . . . . . . 230 xvi Contents 12.8 Roles and Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 12.8.1 Classes and Roles: An Example . . . . . . . . . . . . . . . . . . . . . . 231 12.8.2 Role Composition and Code Reuse . . . . . . . . . . . . . . . . . . . . 233 12.8.3 Roles, Classes, Objects, and Types . . . . . . . . . . . . . . . . . . . . 234 12.9 Method Delegation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 12.10 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 12.11 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 12.11.1 Private Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 12.11.2 Constructing Objects with Private Attributes . . . . . . . . . . . . . . 239 12.12 Interface and Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . 242 12.13 Object-Oriented Programming: A Tale . . . . . . . . . . . . . . . . . . . . . 242 12.13.1 The Fable of the Shepherd . . . . . . . . . . . . . . . . . . . . . . . . . 243 12.13.2 The Moral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 12.14 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 12.14.1 The Raku Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 12.14.2 Getting Some Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 12.14.3 Stepping Through the Code . . . . . . . . . . . . . . . . . . . . . . . . 245 12.14.4 Stopping at the Right Place with Breakpoints . . . . . . . . . . . . . . 246 12.14.5 Logging Information with Trace Points . . . . . . . . . . . . . . . . . 246 12.14.6 Stepping Through a Regex Match . . . . . . . . . . . . . . . . . . . . 246 12.15 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Regexes and Grammars 247 249 13.1 A Brief Refresher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 13.2 Declarative Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 13.3 Captures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 13.4 Named Rules (a.k.a. Subrules) . . . . . . . . . . . . . . . . . . . . . . . . . . 252 13.5 Grammars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 13.6 Grammar Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 13.7 Actions Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 13.8 A grammar for Parsing JSON . . . . . . . . . . . . . . . . . . . . . . . . . . 259 13.8.1 The JSON Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 Contents xvii 13.8.2 Our JSON Sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 13.8.3 Writing the JSON Grammar Step by Step . . . . . . . . . . . . . . . . 260 13.9 13.8.4 The JSON Grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 13.8.5 Adding Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 Inheritance and Mutable Grammars . . . . . . . . . . . . . . . . . . . . . . 266 13.10 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 13.11 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 13.12 Exercise: A Grammar for an Arithmetic Calculator . . . . . . . . . . . . . . 269 14 Functional Programming in Raku 14.1 Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 271 14.1.1 A Refresher on Functions as First-Class Objects . . . . . . . . . . . . 271 14.1.2 Anonymous Subroutines and Lambdas . . . . . . . . . . . . . . . . . 273 14.1.3 Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.2 274 List Processing and Pipeline Programming . . . . . . . . . . . . . . . . . . 276 14.2.1 Feed and Backward Feed Operators . . . . . . . . . . . . . . . . . . . 277 14.2.2 The Reduction Metaoperator . . . . . . . . . . . . . . . . . . . . . . . 278 14.2.3 The Hyperoperator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 14.2.4 The Cross (X) and Zip (Z) Operators . . . . . . . . . . . . . . . . . . . 279 14.3 14.2.5 List Operators, a Summary . . . . . . . . . . . . . . . . . . . . . . . . 279 14.2.6 Creating New Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Creating Your Own Map-Like Functions . . . . . . . . . . . . . . . . . . . . 283 14.3.1 Custom Versions of map, grep, etc. . . . . . . . . . . . . . . . . . . . . 283 14.3.2 Our Own Version of a Sort Function . . . . . . . . . . . . . . . . . . . 284 14.3.3 An Iterator Version of map . . . . . . . . . . . . . . . . . . . . . . . . 286 14.3.4 An Iterator Version of grep . . . . . . . . . . . . . . . . . . . . . . . . 287 14.4 The gather and take Construct . . . . . . . . . . . . . . . . . . . . . . . . . . 289 14.5 Lazy Lists and the Sequence Operator . . . . . . . . . . . . . . . . . . . . . 291 14.6 14.5.1 The Sequence Operator . . . . . . . . . . . . . . . . . . . . . . . . . . 291 14.5.2 Infinite Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 14.5.3 Using an Explicit Generator . . . . . . . . . . . . . . . . . . . . . . . . 293 Currying and the Whatever Operator . . . . . . . . . . . . . . . . . . . . . 295 xviii Contents 14.6.1 Creating a Curried Subroutine . . . . . . . . . . . . . . . . . . . . . . 295 14.6.2 Currying an Existing Subroutine with the assuming Method . . . . . 296 14.6.3 Currying with the Whatever Star Parameter . . . . . . . . . . . . . . 297 14.7 Using a Functional Programming Style . . . . . . . . . . . . . . . . . . . . . 298 14.7.1 The Merge Sort Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . 298 14.7.2 A Non-Functional Implementation of Merge Sort . . . . . . . . . . . 298 14.7.3 A Functional Implementation of Merge Sort . . . . . . . . . . . . . . 300 14.8 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 14.9 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304 14.10 Exercise: Quick Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 15 Some Final Advice 307 15.1 Make it Clear, Keep it Simple . . . . . . . . . . . . . . . . . . . . . . . . . . 307 15.2 Dos and Donts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 15.3 Use Idioms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 15.4 Whats Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 A Solutions to the Exercises A.1 315 Exercises of Chapter 3: Functions and Subroutines . . . . . . . . . . . . . . 315 A.1.1 Exercise 3.1: Subroutine right-justify (p. 46) . . . . . . . . . . . . . . . 315 A.1.2 Exercise 3.2: Subroutine do-twice (p. 46) . . . . . . . . . . . . . . . . . 316 A.1.3 Exercise 3.3: Subroutine print-grid (p. 47) . . . . . . . . . . . . . . . . 318 A.2 Exercises of Chapter 4: Conditionals and Recursion . . . . . . . . . . . . . 320 A.2.1 Subroutine do-n-times, Exercise Suggested in Section 4.12 (p. 61) . . 320 A.2.2 Exercise 4.1: Days, Hours, Minutes, and Seconds (p. 65) . . . . . . . . 320 A.2.3 Exercise 4.2: Fermats Theorem (p. 66) . . . . . . . . . . . . . . . . . . 321 A.2.4 Exercise 4.3: Is it a Triangle? (p. 66) . . . . . . . . . . . . . . . . . . . . 322 A.2.5 Exercise 4.4: The Fibonacci Numbers (p. 66) . . . . . . . . . . . . . . . 323 A.2.6 Exercise 4.5: The recurse Subroutine (p. 67) . . . . . . . . . . . . . . A.3 323 Exercises of Chapter 5: Fruitful Functions . . . . . . . . . . . . . . . . . . . 325 A.3.1 Compare, exercise at the end of Section 5.1 (p. 70) . . . . . . . . . . . 325 A.3.2 Hypotenuse, exercise at the end of Section 5.2 (p. 72) . . . . . . . . . 326 Contents xix A.3.3 Chained Relational Operators(in Section 5.4) . . . . . . . . . . . . . . 327 A.3.4 The Ackermann Function (Exercise 5.2) . . . . . . . . . . . . . . . . . 327 A.3.5 Palindromes (Exercise 5.3) . . . . . . . . . . . . . . . . . . . . . . . . . 328 A.3.6 Powers (Exercise 5.4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 A.3.7 Finding the GCD of Two Numbers, Exercise 5.5 (p. 84) . . . . . . . . 330 A.4 A.5 Exercises of Chapter 6 (Iteration) . . . . . . . . . . . . . . . . . . . . . . . . 332 A.4.1 Exercise 6.1: Square Root (p. 96) . . . . . . . . . . . . . . . . . . . . . 332 A.4.2 Exercise 6.2: Pi Estimate (p. 96) . . . . . . . . . . . . . . . . . . . . . . 333 Exercises of Chapter 7 (Strings) . . . . . . . . . . . . . . . . . . . . . . . . . 334 A.5.1 Exercise in Section 7.3: String Traversal (p. 104) . . . . . . . . . . . . 334 A.5.2 Exercise in Section 7.3: The Ducklings (p. 104) . . . . . . . . . . . . . 335 A.5.3 Exercise in Section 7.3: Counting the Letters of a String (p. 104) . . . 336 A.5.4 Section 7.5: Simulating a Regex with a Loop (p. 106) . . . . . . . . . . 336 A.5.5 Exercises in Subsection 7.7.8: Regex Exercises (p. 115) . . . . . . . . . 338 A.5.6 Exercise in Section 7.10: is-reverse Subroutine (p. 122) . . . . . . . 341 A.5.7 Exercise 7.1: Counting Letters (p. 123) . . . . . . . . . . . . . . . . . . 341 A.5.8 Exercise 7.2: Lowercase Letters (p. 123) . . . . . . . . . . . . . . . . . 342 A.5.9 Exercise 7.3: Caesars Cipher (p. 125) . . . . . . . . . . . . . . . . . . 344 A.6 Exercises of Chapter 8 (Word Play) . . . . . . . . . . . . . . . . . . . . . . . 345 A.6.1 Exercise 8.7: Consecutive Double Letters (p. 136) . . . . . . . . . . . . 345 A.6.2 Exercise 8.8: Palindromes in Odometers (p. 137) . . . . . . . . . . . . 346 A.6.3 Exercise 8.9: Palindromes in Ages (p. 137) . . . . . . . . . . . . . . . . 347 A.7 Exercises of Chapter 9 (Arrays and Lists) . . . . . . . . . . . . . . . . . . . . 348 A.7.1 Exercise of Section 9.4: Implementing a Queue (p. 145) . . . . . . . . 348 A.7.2 Exercise of Section 9.5: Other Ways to Modify an Array (p. 147) . . . 352 A.7.3 Exercise of Section 9.8: Mapping and Filtering the Elements of a List (p. 154) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 A.7.4 Exercise of Section 9.12: Advanced Sorting Techniques (p. 160) . . . 354 A.7.5 Exercise 9.1: Nested Sum (p. 162) . . . . . . . . . . . . . . . . . . . . . 355 A.7.6 Exercise 9.2: Cumulative Sum (p. 162) . . . . . . . . . . . . . . . . . . 356 A.7.7 Exercise 9.3: Middle (p. 162) . . . . . . . . . . . . . . . . . . . . . . . . 357 A.7.8 Exercise 9.4: Chop (p. 162) . . . . . . . . . . . . . . . . . . . . . . . . . 357 xx Contents A.7.9 Exercise 9.5: Subroutine is-sorted (p. 163) . . . . . . . . . . . . . . . 358 A.7.10 Exercise 9.6: Subroutine is-anagram (p. 163) . . . . . . . . . . . . . . 358 A.7.11 Exercise 9.7: Subroutine has-duplicates (p. 163) . . . . . . . . . . . 359 A.7.12 Exercise 9.8: Simulating the Birthday Paradox (p. 163) . . . . . . . . . 361 A.7.13 Exercise 9.9: Comparing push and unshift (p. 163) . . . . . . . . . . 362 A.7.14 Exercise 9.10: Bisection Search in a List (p. 163) . . . . . . . . . . . . . 363 A.7.15 Exercise 9.11: Reverse Pairs (p. 164) . . . . . . . . . . . . . . . . . . . 365 A.7.16 Exercise 9.12: Interlocking Words (p. 164) . . . . . . . . . . . . . . . . 367 A.8 Exercises of Chapter 10 (Hashes) . . . . . . . . . . . . . . . . . . . . . . . . 368 A.8.1 Exercise at the end of Section 10.1: A hash Is a Mapping (p. 167) . . . 368 A.8.2 Exercise 10.1: Storing the Word List into a Hash (p. 181) . . . . . . . . 369 A.8.3 Exercise 10.2: Memoizing the Ackermann Function (p. 181) . . . . . 369 A.8.4 Exercise 10.3: Finding Duplicates with a Hash (p. 181) . . . . . . . . 371 A.9 A.8.5 Exercise 10.4: Rotate Pairs (p. 181) . . . . . . . . . . . . . . . . . . . . 371 A.8.6 Exercise 10.5: Homophones (p. 181) . . . . . . . . . . . . . . . . . . . 372 Exercises of Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 A.9.1 Exercise in Section 11.2: the given ... when Statement (p. 185) . . 374 A.9.2 Exercise in Section 11.11: Constructing New Operators (p. 195) . . . 375 A.9.3 Exercise in Section 11.12: Sets, Bags and Mixes (p. 197) . . . . . . . . 377 A.9.4 Exercise in Section 11.13: Random Words (p. 198) . . . . . . . . . . . 378 A.9.5 Exercise in Section 11.14: Markov Analysis (p. 200) . . . . . . . . . . 379 A.9.6 Exercises on the Huffman Code in Section 11.19 (p. 208) . . . . . . . 381 A.10 Exercises of Chapter 13: Regexes and Grammars . . . . . . . . . . . . . . . 388 A.10.1 Exercise in Section 13.1: Getting the February Dates Right (p. 254) . . 388 A.10.2 Exercise 13.12 (p. 269): A Grammar for an Arithmetic Calculator . . 390 A.11 Exercises of Chapter 14: Functional Programming . . . . . . . . . . . . . . 393 A.11.1 Exercise 14.10: Making a Functional Implementation of Quick Sort) . 393 Part I Starting with the Basics 3 This book has been divided in two parts. The main reason for that is that I wanted to make a distinction between on the one hand relatively basic notions that are really needed for any programmer using Raku, and on the other hand more advanced concepts that a good programmer needs to know but may be less often needed in the day-to-day development work. The first eleven chapters (a bit more than 200 pages) which make up this first part are meant to teach the concepts that every programmer should know: variables, expressions, statements, functions, conditionals, recursion, operator precedence, loops, etc., as well as the basic data structures commonly used, and the most useful algorithms. These chapters can, I believe, be the basis for a one-semester introductory course on programming. Of course, the professor or teacher that wishes to use this material is entirely free to skip some details from this Part 1 (and also to include sections from Part 2), but, at least, I have provided some guidelines on how I think this book could be used to teach programming using the Raku language. The second part focuses on different programming paradigms and more advanced programming techniques that are in my opinion of paramount importance, but should probably be studied in the context of a second, more advanced, semester. For now, lets get down to the basics. It is my hope that you will enjoy the trip. 4 Chapter 1 The Way of the Program The goal of this book is to teach you to think like a computer scientist. This way of thinking combines some of the best features of mathematics, engineering, and natural science. Like mathematicians, computer scientists use formal languages to denote ideas (specifically computations). Like engineers, they design things, assembling components into systems and evaluating tradeoffs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions. The single most important skill for a computer scientist is problem solving. Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice problem-solving skills. Thats why this chapter is called, The Way of the Program. On one level, you will be learning to program, a useful skill by itself. On another level, you will use programming as a means to an end. As we go along, that end will become clearer. 1.1 What is a Program? A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document, or something graphical, like processing an image or playing a video. The details look different in different languages, but a few basic instructions appear in just about every language: Input Get data from the keyboard, a file, the network, a sensor, a GPS chip or some other device. Output Display data on the screen, save it in a file, send it over the network, act on a mechanical device, etc. Math Perform basic mathematical operations like addition and multiplication. 6 Chapter 1. The Way of the Program Conditional execution Check for certain conditions and run the appropriate code. Repetition Perform some action repeatedly, usually with some variation. Believe it or not, thats pretty much all there is to it. Every program youve ever used, no matter how complicated, is made up of instructions that look pretty much like these. So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions. Using or calling these subtasks makes it possible to create various levels of abstraction. You have probably been told that computers only use 0s and 1s at the lowest level; but we usually dont have to worry about that. When we use a word processor to write a letter or a report, we are interested in files containing text and some formatting instructions, and with commands to change the file or to print it; fortunately, we dont have to care about the underlying 0s and 1s; the word-processing program offers us a much higher view (files, commands, etc.) that hides the gory underlying details. Similarly, when we write a program, we usually use and/or create several layers of abstraction, so that, for example, once we have created a subtask that queries a database and stores the relevant data in memory, we no longer have to worry about the technical details of the subtask. We can use it as a sort of black box that will perform the desired operation for us. The essence of programming is to a very large extent this art of creating these successive layers of abstraction so that performing the higher level tasks becomes relatively easy. 1.2 Running Raku One of the challenges of getting started with Raku is that you might have to install Raku and related software on your computer. If you are familiar with your operating system, and especially if you are comfortable with the shell or command-line interface, you will have no trouble installing Raku. But for beginners, it can be painful to learn about system administration and programming at the same time. To avoid that problem, you can start out running Raku in a web browser. You might want to use a search engine to find such a site. Currently, the easiest is probably to connect to the https://repl.it/languages/raku site, where you can type some Raku code in the main window, run it, and see the result in the output window below. Another possibility you might want to try is the https://glot.io/new/raku site. There are probably some others. Sooner or later, however, you will really need to install Raku on your computer. The easiest way to install Raku on your system is to download Rakudo Star (a distribution of Raku that contains the Rakudo Raku compiler, documentation and useful modules): follow the instructions for your operating system at http://rakudo.org/ how-to-get-rakudo/ and at https://raku.org/downloads/. You may also want to look at third-party packages using for example Docker or Chocolately. As of this writing, the most recent specification of the language is Raku version 6d (v6.d), and the most recent release available for download is Rakudo Star 2019.03; the examples in this book should all run with this version. You can find out the installed version by issuing the following command at the operating system prompt: 1.3. The First Program 7 $ raku -v This is Rakudo Star version 2019.03.1 built on MoarVM version 2019.03 implementing Perl 6.d. However, you should probably download and install the most recent version you can find. The output (warnings, error messages, etc.) youll get from your version of Raku might in some cases slightly differ from what is printed in this book, but these possible differences should essentially be only cosmetic. Raku is derived from Perl, and it intends to carry forward the high ideals of the Perl community. But, compared to Perl 5, Raku is not just a new version of Perl. It does not aim at replacing Perl 5. Raku is really a new programming language, with a syntax that is similar to Perl 5. The Raku interpreter is a program that reads and executes Raku code. It is sometimes called REPL (for read, evaluate, print, loop). Depending on your environment, you might start the interpreter by clicking on an icon, or by typing raku on a command line. When it starts, you should see output like this: To exit type 'exit' or '^D' (Possibly some information about Raku and related software) > The last line with > is a prompt that indicates that the REPL is ready for you to enter code. If you type a line of code and hit Enter, the interpreter displays the result: > 1 + 1 2 > You can type exit at the REPL prompt to exit the REPL. Now youre ready to get started. From here on, we assume that you know how to start the Raku REPL and run code. 1.3 The First Program Traditionally, the first program you write in a new language is called Hello, World because all it does is display the words Hello, World. In Raku, it looks like this: > say "Hello, World"; Hello, World > This is an example of what is usually called a print statement, although it doesnt actually print anything on paper and doesnt even use the print keyword 1 (keywords are words which have a special meaning to the language and are used by the interpreter to recognize the structure of the program). The print statement displays a result on the screen. In this 1 Raku also has a print function, but the say built-in function is used here because it adds a new line character to the output. 8 Chapter 1. The Way of the Program case, the result is the words Hello, World. The quotation marks in the program indicate the beginning and end of the text to be displayed; they dont appear in the result. The semi-colon ; at the end of the line indicates that this is the end of the current statement. Although a semi-colon is technically not needed when running simple code directly under the REPL, it is usually necessary when writing a program with several lines of code, so you might as well just get into the habit of ending code instructions with a semi-colon. Many other programming languages would require parentheses around the sentence to be displayed, but this is usually not necessary in Raku. 1.4 Arithmetic Operators After Hello, World, the next step is arithmetic. Raku provides operators, which are special symbols that represent computations like addition and multiplication. The operators +, -, *, and / perform addition, subtraction, multiplication and division, as in the following examples under the REPL: > 40 + 2 42 > 43 - 1 42 > 6 * 7 42 > 84 / 2 42 Since we use the REPL, we dont need an explicit print statement in these examples, as the REPL automatically prints out the result of the statements for us. In a real program, you would need a print statement to display the result, as well see later. Similarly, if you run Raku statements in the web browser mentioned in Section 1.2, you will need a print statement to display the result of these operations. For example: say 40 + 2; # -> 42 Finally, the operator ** performs exponentiation; that is, it raises a number to a power: > 6**2 + 6 42 In some other languages, the caret (^) or circumflex accent is used for exponentiation, but in Raku it is used for some other purposes. 1.5 Values and Types A value is one of the basic things a program works with, like a letter or a number. Some values we have seen so far are 2, 42, and "Hello, World". 1.5. Values and Types 9 These values belong to different types: 2 is an integer, 40 + 2 is also an integer, 84/2 is a rational number, and 'Hello, World' is a string, so called because the characters it contains are strung together. If you are not sure what type a value has, Raku can tell you: > say (Int) > say (Int) > say (Rat) > say (Rat) > say (Str) > 42.WHAT; (40 + 2).WHAT; (84 / 2).WHAT; (42.0).WHAT ("Hello, World").WHAT; In these instructions, .WHAT is known as an introspection method, that is a kind of method which will tell you what (of which type) the preceding expression is. 42.WHAT is an example of the dot syntax used for method invocation: it calls the .WHAT built-in on the 42 expression (the invocant) and provides to the say function the result of this invocation, which in this case is the type of the expression. Not surprisingly, integers belong to the type Int, strings belong to Str and rational numbers belong to Rat. Although 40 + 2 and 84 / 2 seem to yield the same result (42), the first expression returns an integer (Int) and the second a rational number (Rat). The number 42.0 is also a rational. The rational type is somewhat uncommon in most programming languages. Internally, these numbers are stored as two integers representing the numerator and the denominator (in their simplest terms). For example, the number 17.3 might be stored as two integers, 173 and 10, meaning that Raku is really storing something meaning the 173 10 fraction. Although this is usually not needed (except for introspection or debugging), you might access these two integers with the following methods: > my $num = 17.3; 17.3 > say $num.WHAT; (Rat) > say $num.numerator, " ", $num.denominator; # say can print a list 173 10 > say $num.nude; # "nude" stands for numerator-denominator (173 10) This may seem anecdotal, but, for reasons which are beyond the scope of this book, this makes it possible for Raku to perform arithmetical operations on rational numbers with a much higher accuracy than most common programming languages. For example, if you try to perform the arithmetical operation 0.3 - 0.2 - 0.1, with most general purpose programming languages (and depending on your machine architecture), you might obtain a result such as -2.77555756156289e-17 (in Perl 5), -2.775558e-17 (in C under gcc), or 10 Chapter 1. The Way of the Program -2.7755575615628914e-17 (Java, Python 3, Ruby, TCL). Dont worry about these values if you dont understand them, let us just say that they are extremely small, but they are not 0, whereas, obviously, the result should really be zero. In Raku, the result is 0 (even to the fiftieth decimal digit): > my $result-should-be-zero = 0.3 - 0.2 - 0.1; 0 > printf "%.50f", $result-should-be-zero; # prints 50 decimal digits 0.00000000000000000000000000000000000000000000000000 In Raku, you might even compare the result of the operation with 0: > say $result-should-be-zero == 0; True Dont do such a comparison with most common programming languages; youre very likely to get a wrong result. What about values like "2" and "42.0"? They look like numbers, but they are in quotation marks like strings. > say '2'.perl; # perl returns a representation of the invocant that could be compiled "2" > say "2".WHAT; (Str) > say '42'.WHAT; (Str) Theyre strings because they are defined within quotes. Although Raku will often perform the necessary conversions for you, it is generally a good practice not to use quotation marks if your value is intended to be a number. When you type a large integer, you might be tempted to use commas between groups of digits, as in 1,234,567. This is not a legal integer in Raku, but it is a legal expression: > 1,234,567 (1 234 567) > Thats actually a list of three different integer numbers, and not what we expected at all! > say (1,234,567).WHAT (List) Raku interprets 1,234,567 as a comma-separated sequence of three integers. As we will see later, the comma is a separator used for constructing lists. You can, however, separate groups of digits with the underscore character _ for better legibility and obtain a proper integer: > 1_234_567 1234567 > say 1_234_567.WHAT (Int) > 1.6. Formal and Natural Languages 1.6 11 Formal and Natural Languages Natural languages are the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally. Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly: Programming languages are formal languages that have been designed to express computations. Formal languages tend to have strict syntax rules that govern the structure of statements. For example, in mathematics the statement 3 + 3 = 6 has correct syntax, but not 3+ = 3$6. In chemistry H2 O is a syntactically correct formula, but 2 Zz is not. Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements. One of the problems with 3+ = 3$6 is that $ is not a legal token in mathematics (at least as far as I know). Similarly, 2 Zz is not legal because there is no chemical element with the abbreviation Zz. The second type of syntax rule, structure, pertains to the way tokens are combined. The equation 3+ = 3 is illegal in mathematics because even though + and = are legal tokens, you cant have one right after the other. Similarly, in a chemical formula, the subscript representing the number of atoms in a chemical compound comes after the element name, not before. This is @ well-structured Engli$h sentence with invalid t*kens in it. This sentence all valid tokens has, but invalid structure with. When you read a sentence in English or a statement in a formal language, you have to figure out the structure (although in a natural language you do this subconsciously). This process is called parsing. Although formal and natural languages have many features in commontokens, structure, and syntaxthere are some differences: Ambiguity Natural languages are full of ambiguity, which people deal with by using contextual clues and other information. Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning. Redundancy In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise. Literalness Natural languages are full of idiom and metaphor. If we say, The penny dropped, there is probably no penny and nothing dropping (this idiom means that someone understood something after a period of confusion). Formal languages mean exactly what they say. Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages. The difference between formal and natural language is like the difference between poetry and prose, but more so: 12 Chapter 1. The Way of the Program Poetry Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response. Ambiguity is not only common but often deliberate. Prose The literal meaning of words is more important, and the structure contributes more meaning. Prose is more amenable to analysis than poetry but still often ambiguous. Programs The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure. Formal languages are more dense than natural languages, so it takes longer to read them. Also, the structure is important, so it is not always best to read from top to bottom, left to right. Instead, learn to parse the program in your head, identifying the tokens and interpreting the structure. Finally, the details matter. Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language. 1.7 Debugging Programmers make mistakes. Programming errors are usually called bugs and the process of tracking them down is called debugging. Programming, and especially debugging, sometimes brings out strong emotions. If you are struggling with a difficult bug, you might feel angry, despondent, or embarrassed. There is evidence that people naturally respond to computers as if they were people. When they work well, we think of them as teammates, and when they are obstinate or rude, we respond to them the same way we respond to rude, obstinate people2 . Preparing for these reactions might help you deal with them. One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture. Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses. And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively. Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming. At the end of each chapter there is a section, like this one, with our suggestions for debugging. I hope they help! 1.8 Glossary Problem solving The process of formulating a problem, finding a solution, and expressing it. Abstraction A way of providing a high-level view of a task and hiding the underlying technical details so that this task becomes easy. Interpreter A program that reads another program and executes it 2 Reeves and Nass, The Media Equation: How People Treat Computers, Television, and New Media Like Real People and Places, (Center for the Study of Language and Information, 2003).) 1.9. Exercises 13 Compiler A program that reads another program and transforms it into executable computer code; there used to be a strong difference between interpreted and compiled languages, but this distinction has become blurred over the last two decades or so. Prompt Characters displayed by the interpreter to indicate that it is ready to take input from the user. Program A set of instructions that specifies a computation. Print statement An instruction that causes the Raku interpreter to display a value on the screen. Operator A special symbol that represents a simple computation like addition, multiplication, or string concatenation. Value One of the basic units of data, like a number or string, that a program manipulates. Type A category of values. The types we have seen so far are integers (type Int), rational numbers (type Rat), and strings (type Str). Integer A type that represents whole numbers. Rational A type that represents numbers with fractional parts. Internally, Raku stores a rational as two integers representing respectively the numerator and the denominator of the fractional number. String A type that represents sequences of characters. Natural language Any one of the languages that people speak that evolved naturally. Formal language Any one of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs; all programming languages are formal languages. Token One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language. Syntax The rules that govern the structure of a program. Parse To examine a program and analyze the syntactic structure. Bug An error in a program. Debugging The process of finding and correcting bugs. 1.9 Exercises Exercise 1.1. It is a good idea to read this book in front of a computer so you can try out the examples as you go. Whenever you are experimenting with a new feature, you should try to make mistakes. For example, in the Hello, world! program, what happens if you leave out one of the quotation marks? What if you leave out both? What if you spell say wrong? This kind of experiment helps you remember what you read; it also helps when you are programming, because you get to know what the error messages mean. It is better to make mistakes now and on purpose than later and accidentally. 14 Chapter 1. The Way of the Program Please note that most exercises in this book are provided with a solution in the appendix. However, the exercises in this chapter and in the next chapter are not intended to let you solve an actual problem but are designed to simply let you experiment with the Raku interpreter; there is no good solution, just try out what is proposed to get a feeling on how it works. 1. If you are trying to print a string, what happens if you leave out one of the quotation marks, or both? 2. You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2? 3. In math notation, leading zeros are OK, as in 02. What happens if you try this in Raku? 4. What happens if you have two values with no operator between them, such as say 2 2;? Exercise 1.2. Start the Raku REPL interpreter and use it as a calculator. 1. How many seconds are there in 42 minutes, 42 seconds? 2. How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile. 3. If you run a 10 kilometer race in 42 minutes, 42 seconds, what is your average pace (time per mile in minutes and seconds)? What is your average speed in miles per hour? Chapter 2 Variables, Expressions and Statements One of the most powerful features of a programming language is the ability to manipulate variables. Broadly speaking, a variable is a name that refers to a value. It might be more accurate to say that a variable is a container that has a name and holds a value. 2.1 Assignment Statements An assignment statement uses the equals sign = and gives a value to a variable, but, before you can assign a value to a variable, you first need to create the variable by declaring it (if it does not already exist): > my $message; # variable declaration, no value yet > $message = 'And now for something completely different'; And now for something completely different > my $number = 42; # variable declaration and assignment 42 > $number = 17; # new assignment 17 > my $phi = 1.618033988; 1.618033988 > This example makes four assignment statements. The first assigns a string to a new variable named $message, the second assigns the integer 42 to $number, the third reassigns the integer 17 to $number, and the fourth assigns the (approximate) value of the golden ratio to $phi. There are two important syntax features to understand here. First, in Raku, variable names start with a so-called sigil, i.e., a special non-alphanumeric character such as $, @, %, &, and some others. This special character tells us and the Raku compiler (the program that reads the code of our program and transforms it into computer 16 Chapter 2. Variables, Expressions and Statements instructions) which kind of variable it is. For example, the $ character indicates that the variables above are all scalar variables, which means that they can contain only one value at any given time. Well see later other types of variables that may contain more than one value. Second, notice that all three variables above are first introduced by the keyword my, which is a way of declaring a new variable. Whenever you create a new variable in Raku, you need to declare it, i.e., tell Raku that youre going to use that new variable; this is most commonly done with the my keyword, which declares a lexical variable. We will explain later what a lexical variable is; lets just say for the time being that it enables you to make your variable local to a limited part of your code. One of the good consequences of the requirement to declare variables before you use them is that, if you accidentally make a typo when writing a variable name, the compiler will usually be able to tell you that you are using a variable that has not been declared previously and thus help you find your error. This has other far-reaching implications which we will examine later. When we wrote at the beginning of this section that a variable has to be declared before it is used (or just when it is used), it plainly means that the declaration has to be before (or at the point of) the variables first use in the text file containing the program. We will see later that programs dont necessarily run from top to bottom in the order in which the lines or code appear in the program file; still, the variable declaration must be before its use in the text file containing the program. If you neglect to declare a variable, you get a syntax error: > $number = 5; ===SORRY!=== Error while compiling
Variable '$number' is not declared at :1 ------> $number = 5; > Please remember that you may obtain slightly different error messages depending on the version of Rakudo you run. The above message was obtained in February 2016; with a newer version (October 2016), the same error is now displayed somewhat more cleanly as: > > $number = 5; ===SORRY!=== Error while compiling: Variable '$number' is not declared at line 2 ------> $number = 5; > A common way to represent variables on paper is to write the name with an arrow pointing to its value. This kind of figure is called a state diagram because it shows what state each of the variables is in (think of it as the variables state of mind). Figure 2.1 shows the result of the previous example. 2.2 Variable Names Programmers generally choose names for their variables that are meaningfulthey document what the variable is used for. 2.2. Variable Names 17 Figure 2.1: State diagram. Variable names can be as long as you like. They can contain both letters and numbers, but user-defined variable names cant begin with a number. Variable names are case-sensitive, i.e., $message is not the same variable as $Message or $MESSAGE. It is legal to use uppercase letters, but it is conventional to use only lower case for most variables names. Some people nonetheless like to use $TitleCase for their variables or even pure $UPPERCASE for some special variables. Unlike most other programming languages, Raku does not require the letters and digits used in variable names to be plain ASCII. You can use all kinds of Unicode letters, i.e., letters from almost any language in the world, so that, for example, $brcke, $pay or $nio are valid variable names, which can be useful for non-English programmers (provided that these Unicode characters are handled correctly by your text editor and your screen configuration). Similarly, instead of using $phi for the name of the golden ratio variable, we might have used the Greek small letter phi, (Unicode code point U+03C6), just as we could have used the Greek small letter pi, , for the well-known circle circumference to diameter ratio: > my $ = (5 ** .5 + 1)/2; # golden ratio 1.61803398874989 > say 'Variable $ = ', $ ; Variable $ = 1.61803398874989 > my $ = 4 * atan 1; 3.14159265358979 > # you could also use the pi or built-in constant: > say pi 3.14159265358979 The underscore character, _, can appear anywhere in a variable name. It is often used in names with multiple words, such as $your_name or $airspeed_of_unladen_swallow. You may even use dashes to create so-called kebab case1 and name those variables $your-name or $airspeed-of-unladen-swallow, and this might make them slightly easier to read: a dash - is valid in variable names provided it is immediately followed by an alphabetical character and preceded by an alphanumerical character. For example, $double-click or $la-nia are legitimate variable names. Similarly, you can use an apostrophe ' (a.k.a. single quote) between letters, so $isn't or $o'brien's-age are valid identifiers. If you give a variable an illegal name, you get a syntax error: > my $76trombones = 'big parade' ===SORRY!=== Error while compiling Cannot declare a numeric variable 1 Because the words appear to be skewered like pieces of food prepared for a barbecue. 18 Chapter 2. Variables, Expressions and Statements at :1 ------> my $76 trombones = "big parade"; > > my $more = 100000; ===SORRY!=== Error while compiling Bogus postfix at :1 ------> my $more = 100000; (...) $76trombones is illegal because it begins with a number. $more is illegal because it contains an illegal character, . If youve ever used another programming language and stumbled across a terse message such as "SyntaxError: invalid syntax", you will notice that the Raku designers have made quite a bit of effort to provide detailed, useful, and meaningful error messages. Many programming languages have keywords or reserved words that are part of the syntax, such as if, while, or for, and thus cannot be used for identifying variables because this would create ambiguity. There is no such problem in Raku: since variable names start with a sigil, the compiler is always able to tell the difference between a keyword and a variable. Names such as $if or $while are syntactically valid variable identifiers in Raku (whether such names make sense is a different matter). 2.3 Expressions and Statements An expression is a combination of terms and operators. Terms may be variables or literals, i.e., constant values such as a number or a string. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions: > 42 42 > my $n = 17; 17 > $n; 17 > $n + 25; 42 > When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of the expression. In this example, $n has the value 17 and $n + 25 has the value 42. A statement is a unit of code that has an effect, like creating a variable or displaying a value, and usually needs to end with a semi-colon ; (but the semi-colon can sometimes be omitted as we will see later): > my $n = 17; 17 > say $n; 17 2.3. Expressions and Statements 19 The first line is an assignment statement that gives a value to $n. The second line is a print statement that displays the value of $n. When you type a statement and then press Enter, the interpreter executes it, which means that it does whatever the statement says. An assignment can be combined with expressions using arithmetic operators. For example, you might write: > my $answer = 17 + 25; 42 > say $answer; 42 The + symbol is obviously the addition operator and, after the assignment statement, the $answer variable contains the result of the addition. The terms on each side of the operator (here 17 and 25) are sometimes called the operands of the operation (an addition in this case). Note that the REPL actually displays the result of the assignment (the first line with 42), so that the print statement was not really necessary in this example under the REPL; from now on, for the sake of brevity, we will generally omit the print statements in the examples where the REPL displays the result. In some cases, you want to add something to a variable and assign the result to that same variable. This could be written: > my $answer = 17; 17 > $answer = $answer + 25; 42 Here, $answer is first declared with a value of 17. The next statement assigns to $answer the current value of $answer (i.e., 17) + 25. This is such a common operation that Raku, like many other programming languages, has a shortcut for this: > my $answer = 17; 17 > $answer += 25; 42 The += operator combines the arithmetic addition operator and the assignment operator to modify a value and apply the result to a variable in one go, so that $n += 2 means: take the current value of $n, add 2, and assign the result to $n. This syntax works with all other arithmetic operators. For example, -= similarly performs a subtraction and an assignment, *= a multiplication and an assignment, etc. It can even be used with operators other than arithmetic operators, such as the string concatenation operator that we will see later. Adding 1 to a variable is a very common version of this, so that there is a shortcut to the shortcut, the increment operator, which increments its argument by one, and returns the incremented value: 20 Chapter 2. Variables, Expressions and Statements > my $n = 17; 17 > ++$n; 18 > say $n; 18 This is called the prefix increment operator, because the ++ operator is placed before the variable to be incremented. There is also a postfix version, $n++, which first returns the current value and then increments the variable by one. It would not make a difference in the code snippet above, but the result can be very different in slightly more complex expressions. There is also a decrement operator --, which decrements its argument by one and also exists in a prefix and a postfix form. 2.4 Script Mode So far we have run Raku in interactive mode, which means that you interact directly with the interpreter (the REPL). Interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy and even tedious. The alternative is to use a text editor and save code in a file called a script and then run the interpreter in script mode to execute the script. By convention, Raku scripts have names that end with .raku, but you could in theory use anything else is you wished (although this is probably not recommended for the sake of clarity). Please make sure that youre really using a text editor and not a word-processing program (such as MS Word, OpenOffice or LibreOffice Writer). There is a very large number of text editors available for free. On Linux, you might use vi (or vim), emacs, gEdit, or nano. On Windows, you may use notepad (very limited) or notepad++. There are also many crossplatform editors or integrated development environments (IDEs) providing a text editor functionality, including padre, eclipse, atom, or Comma, which is specifically designed for Raku. Many of these provide various syntax highlighting capabilities, which might help you use correct syntax (and find some syntax errors). Once youve saved your code into a file (say, for example, my_script.raku), you can run the program by issuing the following command at the operating system prompt (for example in a Linux console or in a cmd window under Windows): raku my_script.raku Because Raku provides both modes, you can test bits of code in interactive mode before you put them in a script. But there are differences between interactive mode and script mode that can be confusing. For example, if you are using the Raku interpreter as a calculator, you might type: > my $miles = 26.2; 26.2 > $miles * 1.61; 42.182 2.5. One-Liner Mode 21 The first line assigns a value to $miles and displays that value. The second line is an expression, so the interpreter evaluates it and displays the result. It turns out that a marathon is about 42 kilometers. But if you type the same code into a script and run it, you get no output at all. In script mode, an expression, all by itself, has no visible effect. Raku actually evaluates the expression, but it doesnt display the value unless you tell it to: my $miles = 26.2; say $miles * 1.61; This behavior can be confusing at first. Lets examine why. A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the print statements execute. For example, consider the following script: say 1; my $x = 2; say $x; It produces the following output: 1 2 The assignment statement produces no output. To check your understanding, type the following statements in the Raku interpreter and see what they do: 5; my $x = 5; $x + 1; Now put the same statements in a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again. 2.5 One-Liner Mode Raku also has a one-liner mode, which enables you to type directly a very short script at the operating system prompt. Under Windows, it might look like this: C:\Users\Laurent>raku -e "my $value = 42; say 'The answer is ', $value;" The answer is 42 The -e option tells the compiler that the script to be run is not saved in a file but instead typed at the prompt between quotation marks immediately after this option. Under Unix and Linux, you would replace double quotation marks with apostrophes (or single quotes) and apostrophes with double quotation marks: 22 Chapter 2. Variables, Expressions and Statements $ raku -e 'my $value = 42; say "The answer is $value";' The answer is 42 The one-liner above may not seem to be very useful, but throwaway one-liners can be very practical to perform simple one-off operations, such as quickly modifying a file not properly formatted, without having to save a script in a separate file before running it. We will not give any additional details about the one-liner mode here, but will give some more useful examples later in this book; for example, Subsection 8.4.1, Subsection A.5.9 (solving the rot-13 exercise), or Subsection A.6.1 (solving the exercise on consecutive double letters). 2.6 Order of Operations When an expression contains more than one operator, the order of evaluation depends on the order of operations or operator precedence. For mathematical operators, Raku follows mathematical convention. The acronym PEMDAS2 is a useful way to remember the rules: Parentheses have the highest (or tightest) precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in ($minute * 100) / 60, even if it doesnt change the result. Exponentiation has the next highest precedence, so 1 + 2**3 is 9 (1 + 8), not 27, and 2 * 3**2 is 18, not 36. Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5. Operators with the same precedence are usually evaluated from left to right (except exponentiation). So in the expression $degrees / 2 * pi, the division happens first and the result is multiplied by pi, which is not the expected result. (Note that pi is not a variable, but a predefined constant in Raku, and therefore does not require a sigil.) To divide by 2, you can use parentheses: my $result = $degrees / (2 * pi); or write $degrees / 2 / pi or $degrees / 2 / , which will divide $degrees by 2, and then divide the result of that operation by (which is equivalent to $degrees divided by 2). I dont work very hard to remember the precedence of operators. If I cant tell by looking at the expression, I use parentheses to make it obvious. If I dont know for sure which of two operators has the higher precedence, then the next person reading or maintaining my code may also not know. 2 US students are sometimes taught to use the "Please Excuse My Dear Aunt Sally" mnemonics to remember the right order of the letters in the acronym. 2.7. String Operations 2.7 23 String Operations In general, you cant perform mathematical operations on strings, unless the strings look so much like numbers that Raku can transform or coerce them into numbers and still make sense, so the following are illegal: '2'-'1a' 'eggs'/'easy' 'third'*'a charm' For example, this produces an error: > '2'-'1a' Cannot convert string to number: trailing characters after number in '1?a' (indicated by ?) in block at :1 But the following expressions are valid because these strings can be coerced to numbers without any ambiguity: > '2'-'1' 1 > '3'/'4' 0.75 The ~ operator performs string concatenation, which means it joins the strings by linking them end-to-end. For example: > my $first = 'throat' throat > my $second = 'warbler' warbler > $first ~ $second throatwarbler The x operator also works on strings; it performs repetition. For example: > 'ab' x 3; ababab > 42 x 3 424242 > 3 x 42 333333333333333333333333333333333333333333 Notice that, although the x operator somewhat looks like the multiplication operator when we write it by hand, x is obviously not commutative, contrary to the * multiplication operator. The first operand is a string or is coerced to a string (i.e., transformed into a string: 42 is coerced to '42'), and the second operand has to be a number or something that can be transformed into a number. 24 2.8 Chapter 2. Variables, Expressions and Statements Comments As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why. For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they start with the # symbol: # compute the percentage of the hour that has elapsed my $percentage = ($minute * 100) / 60; In this case, the comment appears on a line by itself. You can also put comments at the end of a line: $percentage = ($minute * 100) / 60; # percentage of an hour Everything from the # to the end of the line is ignoredit has no effect on the execution of the program. Comments are most useful when they document nonobvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is more useful to explain why. This comment is redundant with the code and useless: my $value = 5; # assign 5 to $value This comment, by contrast, contains useful information that is not in the code: my $velocity = 5; # velocity in meters/second. Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff. 2.9 Debugging Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful to distinguish between them in order to track them down more quickly. Syntax error Syntax refers to the structure of a program and the rules about that structure. For example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8) is a syntax error. 3 If there is a syntax error anywhere in your program, Raku displays an error message and quits without even starting to run your program, and you will obviously not be able to run the program. During the first few weeks of your programming career, you might spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer errors and find them faster. 3 We are using syntax error here as a quasi-synonym for compile-time error; they are not exactly the same thing (you may in theory have syntax errors that are not compile-time errors and the other way around), but they can be deemed to be the same for practical purposes here. In Raku, compile-time errors have the ===SORRY!=== string at the beginning of the error message. 2.10. Glossary 25 Runtime error The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened. Runtime errors are rare in the simple programs you will see in the first few chapters, so it might be a while before you encounter one. We have seen one example of such errors, though, at the beginning of Section 2.7 (p. 23), when we tried to subtract '2'-'1a'. Semantic error The third type of error is semantic, which means related to meaning. If there is a semantic error in your program, it will run without generating error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do, but not what you intended it to do. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing. 2.10 Glossary Variable Informally, a name that refers to a value. More accurately, a variable is a container that has a name and holds a value. Assignment A statement that assigns a value to a variable. State diagram A graphical representation of a set of variables and the values they refer to. Keyword A reserved word that is used to parse a program; in many languages, you cannot use keywords like if, for, and while as variable names. This problem usually does not occur in Raku because variable names begin with a sigil. Operand A value or term next to an operator that is used in its evaluation. Term A variable or a literal value. Expression A combination of operators and terms that represents a single result. Evaluate To simplify an expression by performing the operations in order to yield a single value. Statement A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements. Statements usually end with a semi-colon. Execute To run a statement and do what it says. interactive mode (or interpreter mode): A way of using the Raku interpreter by typing code at the prompt. Script mode A way of using the Raku interpreter to read code from a script and run it. one-liner mode: A way of using the Raku interpreter to read code passed at the operating system prompt and run it. Script A program stored in a file. 26 Chapter 2. Variables, Expressions and Statements Order of operations Rules governing the order in which expressions involving multiple operators and operands are evaluated. It is also called operator precedence. Concatenate To join two string operands end-to-end. Comment Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program. Syntax error An error in a program that makes it impossible to parse (and therefore impossible to compile and to run). Exception An error that is detected while the program is running. Semantics The meaning of a program. Semantic error An error in a program that makes it do something other than what the programmer intended. 2.11 Exercises Exercise 2.1. Repeating our advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode (under the REPL) and make errors on purpose to see what goes wrong. Weve seen that $n = 42 is legal. What about 42 = $n? How about $x = $y = 1? (Hint: note that you will have to declare both variables, for example with a statement such as my $x; my $y; or possibly my ($x, $y);, before you can run the above.) In some languages, statements dont have to end with a semi-colon, ;. What happens in script mode if you omit a semi-colon at the end of a Raku statement? What if you put a period at the end of a statement? In math notation you can multiply x and y like this: xy. What happens if you try that in Raku? Exercise 2.2. Practice using the Raku interpreter as a calculator: 1. The volume of a sphere with radius r is 34 r3 . What is the volume of a sphere with radius 5? 2. Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies? 3. If I leave my house at 6:52 a.m. and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time is it when I complete my running exercise? Chapter 3 Functions In the context of programming, a function is usually a named sequence of statements that performs a computation. In Raku, functions are often also called subroutines and the two terms can (for now) be considered as more or less equivalent. When you define a function, you specify the name and the sequence of statements. Later, when you want to perform a computation, you can call the function by name and this will run the sequence of statements contained in the function definition. Raku comes with many built-in functions that are quite handy. Youve already seen some of them: for example, say is a built-in function, and we will see many more in the course of this book. And if Raku doesnt already have a function that does what you want, you can build your own. This teaches you the basics of functions and how to build new ones. 3.1 Function Calls We have already seen examples of function calls: > say 42; 42 The name of the function is say. The expression following the function name is called the argument of the function. The say function causes the argument to be displayed on the screen. If you need to pass several values to a function, then just separate the arguments with commas: > say "The answer to the ultimate question is ", 42; The answer to the ultimate question is 42 Many programming languages require the arguments of a function to be inserted between parentheses. This is not required (and usually not recommended) in Raku for most built-in functions (except when needed for precedence), but if you do use parentheses, you should make sure to avoid inserting spaces between the function name and the opening parenthesis. For example, the round function usually takes two arguments: the value to be rounded and the unit or scale. You may call it in any of the following ways: 28 Chapter 3. Functions > round 42.45, 1; 42 > round 42.45, .1; 42.5 > round(42.45, .1); 42.5 > round( 42.45, .1); 42.5 # But not: round (42.45, .1); # Space is OK *after* the opening paren Experienced Raku programmers usually prefer to omit the parentheses when they can. Doing so makes it possible to chain several functions with a visually cleaner syntax. Consider for example the differences between these two calls: > say round 42.45, 1; 42 > say(round(42.45, 1)); 42 The second statement is explicitly saying what is going on, but the accumulation of parentheses actually makes things not very clear. By contrast, the first statement can be seen as a pipeline to be read from right to left: the last function on the right, round, is taking two arguments, 42.45, 1, and the value produced by round is passed as an argument to say. It is common to say that a function takes one or several arguments and returns a result. The result is also called the return value. Raku provides functions that convert values from one type to another. When called with only one argument, the round function takes any value and converts it to an integer, if it can, or complains otherwise: > round 42.3; 42 > round "yes" Cannot convert string to number: base-10 number must begin with valid digits or '.' in ' yes' (indicated by ) in block at line 1 Note that, in Raku, many built-in functions can also use a method invocation syntax with the so-called dot notation. The following statements display the same result: > round 42.7; 43 > 42.7.round; 43 # Function call syntax # Method invocation syntax The round function can round off rational and floating-point values to integers. There is an Int method that can also convert noninteger numerical values into integers, but it doesnt round off; it chops off the fraction part: > round 42.7 43 > 42.7.Int 42 3.1. Function Calls 29 Well come back to methods in the next section. The Rat built-in function converts integers and strings to rational numbers (if possible): > say 4.Rat; 4 > say 4.Rat.WHAT; (Rat) > say Rat(4).WHAT; (Rat) > say Rat(4).nude; (4 1) > say Rat('3.14159'); 3.14159 > say Rat('3.14159').nude (314159 100000) (As you might remember from Section 1.5, the nude method displays the numerator and denominator of a rational number.) Finally, Str converts its argument to a string: > say 42.Str.WHAT (Str) > say Str(42).WHAT; (Str) Note that these type conversion functions often dont need to be called explicitly, as Raku will in many cases try to do the right thing for you. For example, if you have a string that looks like an integer number, Raku will coerce the string to an integer for you if you try to apply an arithmetic operation on it: > say "21" * "2"; 42 Similarly, integers will be coerced to strings if you apply the string concatenation operator to them: > say 4 ~ 2; 42 > say (4 ~ 2).WHAT; (Str) The coercion can even happen twice within the same expression if needed: > say (4 ~ 1) + 1; 42 > say ((4 ~ 1) + 1).WHAT; (Int) 30 3.2 Chapter 3. Functions Functions and Methods A method is similar to a functionit takes arguments and returns a valuebut the calling syntax is different. With a function, you specify the name of the function followed by its arguments. A method, by contrast, uses the dot notation: you specify the name of the object on which the method is called, followed by a dot and the name of the method (and possibly additional arguments). A method call is often called an invocation . The deeper differences between functions and methods will become apparent much later, when studying object-oriented programming (in Chapter 12). For the time being, we can consider that the difference is essentially a matter of a different calling syntax when using Rakus built-ins. Most of Raku built-ins accept both a function call syntax and a method invocation syntax. For example, the following statements are equivalent: > say 42; 42 > 42.say; 42 # function call syntax # method invocation syntax You can also chain built-in routines with both syntactic forms: > 42.WHAT.say; (Int) > say WHAT 42; (Int) > say 42.WHAT; (Int) # method syntax # function syntax # mixed syntax It is up to you to decide whether you prefer one form or the other, but we will use both forms, if only to get you used to both of them. 3.3 Math functions Raku provides most of the familiar mathematical functions. For some less common functions, you might need to use a specialized module such as Math::Matrix or Math::Trig. A module is a file that contains a collection of related functions. Before we can use the functions in a module, we have to import it with a use statement: use Math::Trig; This statement will import a number of functions that you will then be able to use as if you had defined them in your main source file, for example deg2rad to perform conversion of angular values from degrees to radians, or rad2deg to perform the opposite conversion. For most common mathematical functions, however, you dont need any math module, as they are included in the core of the language: 3.3. Math functions 31 > my $noise-power = 5.5; 5.5 > my $signal-power = 125.6; 125.6 > my $decibels = 10 * log10 $signal-power / $noise-power; 13.5862694990693 This first example uses log10 (common logarithm) to compute a signal-to-noise ratio in decibels (assuming that signal-power and noise-power are defined in the proper units). Raku also provides a log function which, when receiving one argument, computes logarithm base e of the argument, and, when receiving two arguments, computes the logarithm of the first argument to the base of the second argument: > say e; 2.71828182845905 > my $val = e ** e; 15.1542622414793 > say log $val; 2.71828182845905 > say log $val, e; 2.71828182845905 > say log 1024, 2; 10 # e is predefined as Euler's constant # natural logarithm # logarithm base e or natural logarithm # binary logarithm or logarithm base 2 Raku also provides most common trigonometric functions: > my $radians = 0.7; 0.7 > my $height = sin $radians; 0.644217687237691 This example finds the sine of $radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, you may use the deg2rad function of the Math::Trig module, or simply divide by 180 and multiply by : > my $degrees = 45; 45 > my $radians = $degrees / 180.0 * pi; # pi, predefined constant 0.785398163397448 > say sin $radians; # should be square root of 2 divided by 2 0.707106781186547 The expression pi is a predefined constant for an approximation of , accurate to about 14 digits. If you know trigonometry, you can check the previous result by comparing it to the square root of two divided by two: > say sqrt(2) / 2; 0.707106781186548 32 Chapter 3. Functions 3.4 Composition So far, we have looked at the elements of a programvariables, expressions, and statementsin isolation, without talking about how to combine them. One of the most useful features of programming languages is their ability to take small building blocks and compose them, i.e., to combine them in such a way that the result of one is the input of another one. For example, the argument of a function can be any kind of expression, including arithmetic operators: > my $degrees = 45; 45 > my $height = sin($degrees / 360.0 * 2 * pi); 0.707106781186547 Here, we have used parentheses for the argument to the sin function to clarify that all the arithmetic operations within the parentheses are completed before the sin function is actually called, so that it will use the result of these operations as its argument. You can also compose function calls: > my $x = 10; 10 > $x = exp log($x+1) 11 Almost anywhere you can put a value, you can put an arbitrary expression, with one exception: the left side of an assignment statement has to be a variable name, possibly along with its declaration. Almost any other expression on the left side is a syntax error 1 : > my $hours = 1; 1 > my $minutes = 0; 0 > $minutes = $hours * 60; # right 60 > $hours * 60 = $minutes; # wrong !! Cannot modify an immutable Int in block at line 1 3.5 Adding New Functions (a.k.a. Subroutines) So far, we have only been using the functions that come with Raku, but it is also possible to add new functions. In Raku, user-defined functions are often called subroutines, but you might choose either word for them. A function definition starts with the sub keyword (for subroutine) and specifies the name of a new subroutine and the sequence of statements that run when the function is called. Here is an example of a subroutine quoting Martin Luther Kings famous "I Have a Dream" speech at the Lincoln Memorial in Washington (1963): 1 We will see rare exceptions to this rule later 3.5. Adding New Functions (a.k.a. Subroutines) 33 sub print-speech() { say "Let freedom ring from the prodigious hilltops of New Hampshire."; say "Let freedom ring from the mighty mountains of New York."; } sub is a keyword that indicates that this is a subroutine definition. The name of the function is print-speech. The rules for subroutine names are the same as for variable names: letters, numbers, and underscores are legal, as well as a dash or an apostrophe between letters, but the first character must be a letter or an underscore. You shouldnt use a language keyword (such as if or while) as the name of a function (in some cases, it might actually work, but it would be very confusing, at least for the human reader). The empty parentheses after the name indicate that this function doesnt take any arguments. They are optional in that case, but are required when parameters need to be defined for the subroutine. The first line of the subroutine definition is sometimes called the header; the rest is called the body. The body has to be a code block placed between curly braces and it can contain any number of statements. Although there is no requirement to do so, it is good practice (and highly recommended) to indent body statements by a few leading spaces, since it makes it easier to figure out visually where the function body starts and ends. Please note that you cannot use a method-invocation syntax for subroutines (such as print-speech) that you write: you must call them with a function call syntax. The strings in the print statements are enclosed in double quotes. In this specific case, single quotes could have been used instead to do the same thing, but there are many cases where they wouldnt do the same thing, so youll have to choose one or the other depending on the circumstances. Most people use double quotes in cases where a single quote (which is also an apostrophe) appears in the string: say "And so we've come here today to dramatize a shameful condition."; Conversely, you might use single quotes when double quotes appear in the string: say 'America has given the Negro people a bad check, a check which has come back marked "insufficient funds."'; There is, however, a more important difference between single quotes and double quotes: double quotes allow variable interpolation, and single quotes dont. Variable interpolation means that if a variable name appears within the double-quoted string, this variable name will be replaced by the variable value; within a single-quoted string, the variable name will appear verbatim. For example: my $var = 42; say "His age is $var."; say 'Her age is $var.'; # -> His age is 42. # -> Her age is $var. 34 Chapter 3. Functions The reason is not that the ladys age should be kept secret. In the first string, $var is simply replaced within the string by its value, 42, because the string is quoted with double quotes; in the second string, $var isnt replaced by its value because single quotes are meant to provide a more verbatim type of quoting mechanism. There are other quoting constructs offering finer control over the way variables and special characters are displayed in the output, but simple and double quotes are the most useful ones. The syntax for calling the new subroutine is the same as for built-in functions: > print-speech(); Let freedom ring from the prodigious hilltops of New Hampshire. Let freedom ring from the mighty mountains of New York. However, you cannot use the method-invocation syntax with such subroutines. We will see much later in this book (see Chapter 12) how to create methods. For the time being, well stick to the function-call syntax. Once you have defined a subroutine, you can use it inside another subroutine. For example, to repeat the previous excerpts of Kings address , we could write a subroutine called repeat_speech: sub repeat-speech() { print-speech(); print-speech(); } And then call repeat-speech: > repeat-speech(); Let freedom ring from Let freedom ring from Let freedom ring from Let freedom ring from the the the the prodigious hilltops mighty mountains of prodigious hilltops mighty mountains of of New Hampshire. New York. of New Hampshire. New York. But thats not really how the speech goes. 3.6 Definitions and Uses Pulling together the code fragments from the previous section, the whole program looks like this: sub print-speech () { say "let freedom ring from the prodigious hilltops of New Hampshire."; say "Let freedom ring from the mighty mountains of New York."; } sub repeat-speech () { print-speech(); print-speech(); } repeat-speech(); 3.7. Flow of Execution 35 This program contains two subroutine definitions: print-speech and repeat-speech. Function definitions get executed just like other statements, but the effect is to create the function. The statements inside the function do not run until the function is called, and the function definition generates no output. You dont have to create a subroutine before you can run it, the function definition may come after its call: repeat-speech; sub repeat-speech() { print-speech; print-speech; } sub print-speech() { # ... } 3.7 Flow of Execution To ensure, for example, that a variable is defined (i.e., populated) before its first use, you have to know the order statements run in, which is called the flow of execution. Execution always begins at the first statement of the program (well, really almost always, but lets say always for the time being). Statements are run one at a time, in order from top to bottom. Subroutine definitions do not alter the flow of execution of the program, but remember that statements inside a function dont run until the function is called. A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, runs the statements there, and then comes back to pick up where it left off. That sounds simple enough, until you remember that one function can call another. While in the middle of one function, the program might have to run the statements in another function. Then, while running that new function, the program might have to run yet another function! Fortunately, Raku is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the code that called it. When it gets to the end of the program, it terminates. In summary, when you read a program, you dont always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution. 3.8 Parameters and Arguments Some of the functions we have seen require arguments. For example, when you call sin you pass a number as an argument. Some functions take more than one argument: for example the round function seen at the beginning of this chapter took two, the number to 36 Chapter 3. Functions be rounded and the scale (although the round function may accept a single argument, in which case the scale is defaulted to 1). Inside the subroutine, the arguments are assigned to variables called parameters. Here is a definition for a subroutine that takes a single argument: sub print-twice($value) { say $value; say $value } This subroutine assigns the argument to a parameter named $value. Another common way to say it is that the subroutine binds the parameter defined in its header to the argument with which it was called. When the above subroutine is called, it prints the content of the parameter (whatever it is) twice. This function works with any argument value that can be printed: > print-twice("Let freedom ring") Let freedom ring Let freedom ring > print-twice(42) 42 42 > print-twice(pi) 3.14159265358979 3.14159265358979 The same rules of composition that apply to built-in functions also apply to programmerdefined subroutines, so we can use any kind of expression as an argument for print-twice: > print-twice('Let freedom ring! ' x 2) Let freedom ring! Let freedom ring! Let freedom ring! Let freedom ring! > print-twice(cos pi) -1 -1 The argument is evaluated before the function is called, so in the examples the expressions 'Let freedom ring! ' x 2 and cos pi are only evaluated once. You can also use a variable as an argument: > my $declaration = 'When in the Course of human events, ...' > print-twice($declaration) When in the Course of human events, ... When in the Course of human events, ... The name of the variable we pass as an argument ($declaration) has nothing to do with the name of the parameter ($value). It doesnt matter what the variable was called back home (in the caller); here, within print-twice, we call the parameter $value, irrespective of the name or content of the argument passed to the subroutine. 3.9. Variables and Parameters Are Local 3.9 37 Variables and Parameters Are Local When you create a variable inside a subroutine with the my keyword, it is local, or, more accurately, lexically scoped, to the function block, which means that it only exists inside the function. For example: sub concat_twice($part1, $part2) { my $concatenation = $part1 ~ $part2; print-twice($concatenation) } This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it: > my $start = 'Let freedom ring from '; > my $end = 'the mighty mountains of New York.'; > concat_twice($start, $end); Let freedom ring from the mighty mountains of New York. Let freedom ring from the mighty mountains of New York. When concat_twice terminates, the variable $concatenation is destroyed. If we try to print it, we get an exception: > say $concatenation; ===SORRY!=== Error while compiling Variable '$concatenation' is not declared at :1 ------> say $concatenation; Parameters are also scoped to the subroutine. For example, outside print-twice, there is no such thing as $value. 3.10 Stack Diagrams To keep track of which variables can be used where, it is sometimes useful to draw a stack diagram. Like state diagrams, stack diagrams show the value of each variable, but they also show the function each variable belongs to. Each function is represented graphically by a frame. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it. The stack diagram for the previous example is shown in Figure 3.1. The frames are arranged in a stack that indicates which function called which, and so on. In this example, print-twice was called by concat_twice, and concat_twice was called by main, which is a special name for the topmost frame. When you create a variable outside of any function, it belongs to main. Each parameter refers to the same value as its corresponding argument. So, $part1 has the same value as start, $part2 has the same value as $end, and $value has the same value as $cat. 38 Chapter 3. Functions Figure 3.1: Stack diagram. 3.11 Fruitful Functions and Void Functions Some of the functions we have used, such as the math functions, return results and are useful only insofar we use that return value; for lack of a better name, we may call them fruitful functions. Other functions, like print-twice, perform an action but dont appear to return a value (it does in fact return a value, True, but we dont care about it). They are sometimes called empty or void functions in some other programming languages. In some programming languages, such as Pascal or Ada, there is a strong distinction between a function (which returns a value) and a procedure (which doesnt); they are even defined with different keywords. This distinction does not apply to Raku and to most modern programming languages. In fact, from a pure syntactic standpoint, Raku functions always return a result. So the distinction between fruitful and void functions does not really exist syntactically, but only semantically, i.e., from the standpoint of the meaning of the program: maybe we need to use the return value, or maybe we dont. Another distinction commonly made is between functions and mutators: functions do not change the initial state of the arguments they were called on, and mutators do modify it. We will not use this distinction here, but it is useful to keep it in mind. When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression: my $height = sin $radians; my $golden = (sqrt(5) + 1) / 2; When you call a function in interactive mode (under the REPL), Raku usually displays the result: > sqrt 5; 2.23606797749979 3.11. Fruitful Functions and Void Functions 39 But in a script, if you call a fruitful function all by itself, the return value is lost forever! In some cases, the compiler will be able to warn you, but not always. For example, consider the following program: my $five = 5; sqrt $five; say $five; It produces the following warning: WARNINGS for /home/Laurent/raku_tests/sqrt.raku: Useless use of "sqrt $five" in expression "sqrt $five" in sink context (line 2) 5 This script computes the square root of 5, but since it doesnt store or display the result, it is not very useful. Void functions might display something on the screen, save some data to a file, modify a variable or an object, or have some other effect, but they generally dont have a return value, or at least not a useful one. If you assign the result to a variable, you may get the return value of the subroutine, the value of the last expression which was evaluated in the function, or a special value such as Any, which essentially means something that has not been defined, or Nil. The subroutines we have written so far were essentially printing things to the screen. In that case, they usually return True, at least when the printing was successful. Although they return a true value, what they return isnt very useful and we can consider them all void for our practical purposes. The following is an example of a very simple fruitful subroutine: > sub square($number) { return $number ** 2 } sub square ($number) { #`(Sub|118134416) ... } > say square 5; 25 The Sub|118134416 message displayed by the REPL is just an internal identifier for the subroutine weve just defined. The return statement instructs the function to terminate the execution of the function at this statement and to return the value of the following expression to the caller. In such a simple case where the program is in fact running the last statement of a function, the return keyword can be omitted since the function will return the value of the last evaluated statement, so that the square subroutine could be written this way: sub square($number) { $number ** 2 } We will be using fruitful functions more intensively in a few chapters. 40 Chapter 3. Functions 3.12 Function Signatures When a function receives arguments, which are stored into parameters, the part of the function definition describing the parameters between parentheses is called the function signature. The function signatures we have seen so far are very simple and consist only of one parameter or possibly a parameter list. Signatures can provide a lot more information about the parameters used by a function. First, you may define the type of the parameters. Some functions make sense only if their parameters are numeric and should probably raise an error if they get a string that cannot be converted to a numeric value. For example, if you define a function half that computes a value equal to its argument divided by 2, it does not make sense to try to compute half of a string that is not numeric. It could be written as follows: sub half(Int $number) { return $number / 2 } say half 84; # -> 42 If this function is called with a string, we get the following error: > say half "Douglas Adams" ===SORRY!=== Error while compiling Calling half(Str) will never work with declared signature (Int $number) at :1 ------> say half "Douglas Adams" The Int type included in the function signature is a type constraint that can help prevent subtle bugs. In some cases, it can also be an annoyance. Consider this code snippet: sub half(Int $number) { $number / 2 } say half "84"; # -> ERROR Because the argument to the half subroutine is "84", i.e., a string, this code will fail with a type error. If we had not included the Int type in the signature, the script would have converted (or coerced) the "84" string to a number, divided it by two, and printed out the expected result: sub half($number) { $number / 2 } say half "84"; # -> 42 In some cases, you want this conversion to occur, in others you dont. It is up to you to decide whether you want strict typing or not, depending on the specific situation and needs. It is probably helpful to use parameter typing in many cases, but it can also become a straitjacket in some situations. Raku lets you decide how strict you want to be about these things. Our original half subroutine has another limitation: it can work only on integers. But a function halving its argument should presumably be useful for rational or even other numbers. You can use the Real or Numeric types to make the function more general (the difference between the two types is that the Numeric type will accept not only Real but also Complex numbers2 ). As it turns out that this half function will also work correctly with complex numbers, choosing a Numeric type opens more possibilities: 2 Complex numbers are a powerful concept of mathematics. They are numbers of the form a + bi, where a and b are usual real number and i an imaginary number such that i2 equals 1. 3.13. Immutable and Mutable Parameters 41 sub half(Numeric $number) { $number / 2 } say half(3+4i); # -> 1.5+2i The following table sums up and illustrates some of the various types we have seen so far. Type Example String "A string", 'Another string', "42" Integer -3, -2, 0, 2, 42 Rational 1/2, 0.5,3,14159, 22/7, 42.0 Real , pi, 2, e, log 42, sin 0.7 Complex 5.4 + 3i 3.13 Immutable and Mutable Parameters By default, subroutine parameters are immutable aliases for the arguments passed to the subroutine. In other words, they cannot be changed within the function and you cannot accidentally modify the argument in the caller: sub plus-three(Int $number) { $number += 3} my $value = 5; say plus-three $value; # ERROR: Cannot assign to an immutable value In some other languages, this behavior is named a call by value semantic: loosely speaking, the subroutine receives (by default) a value rather than a variable, and the parameter therefore cannot be modified. If you want to change the value of the parameter within the subroutine (but without changing the argument in the caller) you can add the is copy trait to the signature: sub plus-three(Int $number is copy) { $number += 3} my $value = 5; say plus-three $value; # 8 say $value; # 5 (unchanged) A trait is a property of the parameter defined at compile time. Here, the $number parameter is modified within the subroutine and the incremented value is returned to the caller and printed as 8, but, within the caller, the variable used as an argument to the function, $value, is not modified (it is still 5). Although this can sometimes be dangerous, you may also want to write a subroutine that modifies its argument at the caller side. For this, you can use the is rw trait in the signature: sub plus-three(Int $number is rw) { $number += 3} my $value = 5; say plus-three $value; # 8 say $value; # 8 ($value modified) With the is rw trait, the $number parameter is now bound to the $value argument, so that any change made using $number within the subroutine will immediately be applied to $value at the caller side, because $number and $value are just different names for the same thing (they both refer to the same memory location). The argument is now fully mutable. In some other languages, this is named a call by reference parameter passing mechanism, because, in those languages, if you pass to a function a reference (or a pointer) to a variable, then it is possible for the function to modify the variable referred to by the reference. 42 Chapter 3. Functions 3.14 Functions and Subroutines as First-Class Citizens Subroutines and other code objects can be passed around as values, just like any variable, literal, or object. Functions are said to be first-class objects or sometimes first-class citizens or higher-order functions. This means that a Raku function (its code, not the value returned by it) is a value you can assign to a variable or pass around as an argument. For example, do-twice is a subroutine that takes a function as an argument and calls it twice: sub do-twice($code) { $code(); $code(); } Here, the $code parameter refers to a function or some other callable code object. This is an example that uses do-twice to call a function named greet twice: sub greet { say "Hello World!"; } do-twice &greet; This will print: Hello World! Hello World! The & sigil placed before the subroutine name in the argument list tells Raku that you are passing around a subroutine or some other callable code object (and not calling the subroutine at the moment). In fact, it would be more idiomatic to also use the & sigil in the do-twice subroutine definition, to better specify that the parameter is a callable code object: sub do-twice(&code) { &code(); &code(); } or even: sub do-twice(&code) { code(); code(); } The syntax with the & sigil has the benefit that it will provide a better error message if you make a mistake and pass something noncallable to do-twice. All the functions we have seen so far had a name, but a function does not need to have a name and can be anonymous. For example, it may be stored directly in a scalar variable: 3.14. Functions and Subroutines as First-Class Citizens 43 my $greet = sub { say "Hello World!"; }; $greet(); # prints "Hello World" do-twice $greet; # prints "Hello World" twice It could be argued that the above $greet subroutine is not really anonymous, since it is stored into a scalar variable that could in a certain way be considered as its name. But the subroutine really has no name; it just happens to be assigned to a scalar variable. Just to show that the subroutine can really have no name at all, consider this: do-twice(sub {say "Hello World!"} ); It will happily print "Hello World" twice. If the do-twice function was declared earlier, you can even simplify the syntax and omit the parentheses: do-twice sub {say "Hello World!"}; For such a simple case where there is no need to pass an argument or return a value, you can even omit the sub keyword and pass a code block directly to the function: do-twice {say "Hello World!"}; do-twice {say "what's up doc"}; As you can see, do-twice is a generic subroutine in charge of just performing twice any function or code block passed to it, without any knowledge about what this function or code block is doing. This is a powerful concept for some relatively advanced programming techniques that we will cover later in this book. Subroutines may also be passed as return values from other subroutines: > sub create-func ($person) { return sub { say "Hello $person!"}} # Creating two greeting functions sub create-func ($person) { #`(Sub|176738440) ... } > my $greet_world = create-func "World"; sub () { #`(Sub|176738592) ... } > my $greet_friend = create-func "dear friend"; sub () { #`(Sub|176739048) ... } # Using the greet functions > $greet_world(); Hello World! > $greet_friend(); Hello dear friend! Here, create-func returns a subroutine greeting someone. It is called twice with two different arguments in order to create two different functions at runtime, $greet_world and $greet_friend. A function such as create-func is sometimes a function factory because you may create as many functions as you like by just calling create-func. This example may seem to be a slightly complicated way of doing something quite simple. At this point, it is just a bit too early to give really useful examples, but this is also a very powerful programming technique. Well come back to these techniques in various places in this book and even devote an entire chapter (chapter 14) to this subject and related topics. 44 Chapter 3. Functions 3.15 Why Functions and Subroutines? It may not be clear why it is worth the trouble to divide a program into functions or subroutines. There are several reasons: Creating a new subroutine gives you an opportunity to name a group of statements, which makes your program easier to read and debug. Subroutines also help making the flow of execution clearer to the reader. Subroutines can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place. Dividing a long program into subroutines allows you to debug the parts one at a time and then assemble them into a working whole. Well-designed subroutines are often useful for many programs. Once you write and debug one, you can reuse it. Creating subroutines is one of the major ways to break up a difficult problem into smaller easier subtasks and to create successive layers of abstraction, which are the key to solve complex problems. Writing good subroutines lets you create black boxes, with a known input and a known output. So you dont have to think about them anymore when youre working on something else. Theyve become a tool. Once youve assembled an electric screwdriver, you dont need to think about how it works internally when you use it to build or repair something. In the current open source world, chances are that your code will have to be understood, maintained, or enhanced by people other than you. Coding has become much more of a social activity than before. Breaking up your code into small subroutines whose purpose is easy to understand will make their work easier. And youll be even more delighted when the person having to maintain or refactor your code is... you. 3.16 Debugging One of the most important programming skills you will acquire is debugging. Although it can sometimes be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming. In some ways debugging is like detective work. You are confronted with clues and you have to infer the processes and events that led to the results you see. Debugging is also like an experimental science. Once you have an idea about what is going wrong, you modify your program and try again. If your hypothesis was correct, you can predict the result of the modification, and you take a step closer to a working program. If your hypothesis was wrong, you have to come up with a new one. As Sherlock Holmes pointed out, When you have eliminated the impossible, whatever remains, however improbable, must be the truth (A. Conan Doyle, The Sign of Four). In cases where you are not able to come up with a hypothesis on whats wrong, you can try to introduce code that you expect to create a certain type of error, a negative hypothesis if you will. Sometimes you can learn a lot from the fact that it didnt create the error that was 3.17. Glossary 45 expected. Making a hypothesis does not necessarily mean you have an idea about how to make it work, it could also be a hypothesis on how it should break. For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want. The idea is that you should start with a working program and make small modifications, debugging them as you go. For example, Linux is an operating system that contains millions of lines of code, but it started out as a simple program Linus Torvalds used to explore the Intel 80386 chip. According to Larry Greenfield, One of Linuss earlier projects was a program that would switch between printing AAAA and BBBB. This later evolved to Linux. (The Linux Users Guide Beta Version 1). 3.17 Glossary Function A named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result. Raku comes with many built-in functions, and you can also create your own. In Raku, user-defined functions are often called subroutines. Function definition A statement that creates a new function, specifying its name, parameters, and the statements it contains. Header The first line of a function definition. Body The sequence of statements inside a function definition, usually in a code block delimited by braces. Parameter A name used inside a subroutine to refer to the value passed as an argument. Function call A statement that runs a function. It consists of the function name followed by an argument list, which may or may not be enclosed within parentheses. Argument A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function. Lexical variable A variable defined inside a subroutine or a code block. A lexical variable defined within a function can only be used inside that function. Return value The result of a function. If a function call is used as an expression, the return value is the value of the expression. Any A special value typically found in variables that havent been assigned a value. It is also a special value returned by some functions that we have called void (because they return something generally useless such as Any). Nil Also a special value sometimes returned by some void subroutines. Module A file that contains a collection of related functions and other definitions. Use statement A statement that reads a module file and usually imports some functions. Composition Using an expression as part of a larger expression, or a statement as part of a larger statement. 46 Chapter 3. Functions Flow of execution The order in which statements run. Stack diagram A graphical representation of a stack of subroutines, their variables, and the values they refer to. Frame A box in a stack diagram that represents a subroutine call. It contains the local variables and parameters of the subroutine. Fruitful function A function or subroutine that returns a useful value. Void function A function or subroutine that does not return a useful value. Function signature The part of the definition of a function (usually between parentheses) that defines its parameters and possibly their types and other properties. Immutable parameter A function or subroutine parameter that cannot be changed within the function body. By default, subroutine parameters are immutable. Trait A property of a function or subroutine parameter that is defined at compile time. First class object Rakus subroutines are said to be higher order objects or first-class objects, because they can be passed around as other subroutines arguments or return values, just as any other objects. Anonymous function A function that has no name. Function factory A function that produces other functions as return values. 3.18 Exercises Exercise 3.1. Write a subroutine named right-justify that takes a string named $input-string as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display. > right-justify('Larry Wall') Larry Wall Hint: use string concatenation and repetition. Also, Raku provides a built-in function called chars that returns the length of a string, so the value of chars 'Larry Wall' or 'Larry Wall'.chars is 10. Solution: A.1.1. Exercise 3.2. We have seen that functions and other code objects can be passed around as values, just like any object. Functions are said to be first-class objects. For example, do-twice is a function that takes a function as an argument and calls it twice: sub do-twice($code) { $code(); $code(); } sub greet { say "Hello World!"; } do-twice(&greet); 3.18. Exercises 47 1. Type this example into a script and test it. 2. Modify do-twice so that it takes two arguments, a function and a value, and calls the function twice, passing the value as an argument. 3. Copy the definition of print-twice from earlier in this chapter to your script. 4. Use the modified version of do-twice to call print-twice twice, passing Whats up doc as an argument. 5. Define a new function called do-four that takes a function and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four. Solution: A.1.2. Exercise 3.3. Note: This exercise should be done using only the statements and other features we have learned so far. 1. Write a subroutine that draws a grid like the following: + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + Hint: to print more than one value on a line, you can print a comma-separated sequence of values: say '+', '-'; The say function prints its arguments with a newline at the end (it advances to the next line). If you dont want to go to the next line, use the print function instead: print '+', ' '; print '-'; The output of these statements is + -. A say statement with an empty string argument ends the current line and goes to the next line. 2. Write a subroutine that draws a similar grid with four rows and four columns. Solution: A.1.3 . Credit: this exercise is based on an exercise in Oualline, Practical C Programming, Third Edition, OReilly Media, 1997. 48 Chapter 3. Functions Chapter 4 Loops, Conditionals, and Recursion The main topic of this chapter is the if statement, which executes different code depending on the state of the program. But first I want to introduce two new operators: integer division and modulo. 4.1 Integer Division and Modulo The integer division operator, div, divides two numbers and rounds down to an integer. For example, suppose the run time of a movie is 105 minutes. You might want to know how long that is in hours. In Raku, conventional division returns a rational number (in many languages, it returns a floating-point number, which is another kind of internal representation for noninteger numbers): > my $minutes = 105; > $minutes / 60; 1.75 But we dont normally write hours with decimal points. Integer division returns the integer number of hours, dropping the fraction part: > my $minutes = 105; > my $hours = $minutes div 60; 1 In arithmetic, integer division is sometimes called Euclidean division, which computes a quotient and a remainder. To get the remainder, you could subtract off one hour in minutes: > my $remainder = $minutes - $hours * 60; 45 50 Chapter 4. Loops, Conditionals, and Recursion An alternative is to use the modulo operator, %, which divides two numbers and returns the remainder: > my $remainder = $minutes % 60; 45 The modulo operator is very common in programming languages and is more useful than it seems. For example, you can check whether one number is divisible by anotherif $dividend % $divisor is zero, then $dividend is divisible by $divisor. This is commonly used, for example, with a divisor equal to 2 in order to determine whether an integer is even or odd. We will see an example of that later in this chapter (see Section 4.5). To tell the truth, Raku also has a specific operator for divisibility, %%. The $dividend %% $divisor expression returns a true value if $dividend % $divisor is equal to 0, that is if $dividend is divisible by $divisor (and false otherwise): > 42 %% 2; True Also, you can extract the rightmost digit or digits from a number with the modulo operator. For example, $x % 10 yields the rightmost digit of $x (in base 10). Similarly, $x % 100 yields the last two digits: > 642 % 100; 42 4.2 Boolean Expressions A Boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two numeric operands and produces True if they are equal and False otherwise: > 5 == 5; True > 5 == 6; False True and False are special values that belong to the type Bool; they are not strings: > say True.WHAT (Bool) > say False.WHAT (Bool) The == operator is one of the numeric relational operators and checks whether the operands are equal; the others are: 4.2. Boolean Expressions $x $x $x $x $x $x != $y > $y < $y >= $y <= $y === $y 51 # # # # # # $x $x $x $x $x $x is not numerically equal to $y is numerically greater than $y is numerically less than $y is numerically greater than or equal to $y is numerically less than or equal to $y and $y are truly identical Although these operations are probably familiar to you, the Raku symbols are different from the mathematical symbols. A common error is to use a single equals sign (=) instead of a double equals sign (==). Remember that = is an assignment operator and == is a relational operator. There is no such thing as =<, and there exists a => operator, but it is not a relational operator, but something completely different (it is, as well see later, a pair constructor). The difference between == and === is that the former operator checks whether the values of the operands are equal and the latter checks whether the operands are truly identical. As an example, consider this: say say say say 42 42 42 42 == 42; == 42.0; === 42; === 42.0; # # # # True True True False These relational operators can only compare numeric values (numbers or variables containing numbers) or values that can be coerced to numeric values, such as, for example, the string "42" which, if used with these operators (except ===), will be coerced to the number 42. For comparing strings (in a lexicographic or pseudo- alphabetic type of comparison), you need to use the string relational operators: $x $x $x $x $x $x $x eq $y ne $y gt $y lt $y ge $y le $y eqv $y # # # # # # # $x $x $x $x $x $x $x is is is is is is is string-wise equal to $y string-wise not equal to $y greater than $y (alphabetically after) less than $y (alphabetically before) greater than or equal to $y less than or equal to $y truly equivalent to $y For example, you may compare (alphabetically) two former US presidents: > 'FDR' eq 'JFK'; False > 'FDR' lt 'JFK'; True # alphabetical comparison Unlike most other programming languages, Raku allows you to chain relational operators transitively, just as in mathematical notation: say 4 < 7 < 12; say 4 < 7 < 5; # True # False 52 Chapter 4. Loops, Conditionals, and Recursion It may be useful to point out that numeric relational operators and string relational operators dont work the same way (and thats a good reason for having different operators), because they dont have the same idea of what is greater than or less than. When comparing two positive integers, a number with four digits is always greater than a number with only two or three digits. For example, 1110 is greater than 886. String comparisons, in contrast, basically follow (pseudo) alphabetical rules: b is greater than aaa, because the commonly accepted rule for string comparisons is to start by comparing the first letter of each string: which string is greater is known if the two letters are different, irrespective of what character comes next; you need to proceed to comparing the second letter of each word only if comparing the first letter of each string led to a draw, and so on. Thus, any word starting with a is less than any word starting with b, irrespective of the length of these words. You may think that this is nitpicking, but this becomes essential when you start sorting items: you really have to think about which type of order (numeric or alphabetical) you want to use. There are also some so-called three-way relational operators, cmp, <=> and leg, but well come back to them when we study how to sort the items of a list. Similarly, we need to learn quite a few other things about Raku before we can do justice to the incredibly powerful and expressive smart match operator, ~~. A final point to be noted about string comparisons is that uppercase letters are always deemed smaller than lowercase letters. So "A," "B," "BB," and "C" are all less than "a," "b," "bb," and "c." We will not go into the details here, but this becomes more complicated (and sometimes confusing) when the strings to be compared contain nonalphabetical characters (or non-ASCII Unicode letters). 4.3 Logical Operators There are three main pairs of logical operators: logical and: and and && logical or: or and || logical not: not and ! The semantics (meaning) of these operators is similar to their meaning in English. For example, $x > 0 and $x < 10 is true only if $x is greater than 0 and less than 10. $n % 2 == 0 and $n % 3 == 0 is true if both conditions are true, that is, if the number is divisible by 2 and by 3, i.e., is in fact divisible by 6 (which could be better written as: $n % 6 == 0 or $n %% 6). $n % 2 == 0 or $n % 3 == 0 is true if either or both of the conditions is true, that is, if the number is divisible by 2 or by 3 (or both). Finally, the not operator negates a Boolean expression, so not (x > y) is true if x > y is false, that is, if x is less than or equal to y. The &&, ||, and ! operators have the same meanings, respectively, as and, or, and not, but they have a tighter precedence, which means that when they stand in an expression 4.3. Logical Operators 53 with some other operators, they have a higher priority of execution. We will come back to precedence later, but lets say for the time being that, in most common cases, the and, or, and not operators will usually do what you want. Strictly speaking, the operands of the logical operators should be Boolean expressions, but Raku, just like many languages partly derived from C, is not very strict on that. The numbers 0 and 0.0 are false; and any nonzero number or nonempty string is interpreted as True: > 42 and True; True This flexibility can be very useful, but there are some subtleties to it that might be confusing. You might want to avoid it unless you know what you are doing. The so built-in function returns a Boolean evaluation of its argument: > say so (0 and True); False Here, the expression (0 and True) is false because 0 is false and the expression could be true only if both arguments of the and operator were true. When several Boolean conditions are linked with some logical operator, Raku will only perform the comparisons that are strictly necessary to figure out the final result, starting with those on the left. For example, if you write: > False and $number > 0; False there is no need to evaluate the second Boolean expression to know that the overall expression will be false. In this case, Raku does not try to check whether the number is positive or even whether it is defined. It is sometimes said that these operators short circuit unnecessary conditions. Similarly, in the following code, the compute-pension subroutine will not even be called if the persons age is less than 65: $age >= 65 and compute-pension(); The same goes with the or operator, but the other way around: if the first boolean expression of an or statement is true, then the next expression will not be evaluated. The following code is thus equivalent to the previous one: $age < 65 or compute-pension(); This can be a way of running the compute-pension subroutine conditionally, depending on the value of the age, and this is sometimes used, notably in idiomatic constructs such as: do-something() or die "could not do something"; which aborts the program if do-something returns a false value, meaning that it was not able to do something so essential that it would not make sense to try to continue running it. We will examine now clearer and much more common ways of running conditional code. 54 4.4 Chapter 4. Loops, Conditionals, and Recursion Conditional Execution In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement: if $number > 0 { say '$number is positive'; } The Boolean expression after if is called the condition. If it is true, the subsequent block of code runs. If not, nothing happens. The block of code may contain any number of statements. It is conventional and highly recommended (although not strictly mandatory from the standpoint of the compiler) to indent the statements in the block, in order to help visualize the control flow of the program, i.e., its structure of execution: with such indentation, we can see much better that the statements within the conditional block will run only if the condition is true. The condition may be a compound Boolean expression: if $n > 0 and $n < 20 and $n %% 2 { say '$n is an even and positive number smaller than 20' } Note that in the say statement above, the final semi-colon has been omitted. When a statement is the last code line of a block, immediately before the curly brace } closing that code block, the final semi-colon is optional and may be omitted, though it might be considered good form to include it. In theory, the overall code snippet above is itself a statement and should also end with a semi-colon after the closing brace. But a closing curly brace followed by a newline character implies a statement separator, so you dont need a semi-colon here and it is generally omitted. 4.5 Alternative Execution A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one runs. Given a $number variable containing an integer, the following code displays two different messages depending on whether the value of the integer is even or odd: if $number % 2 == 0 { say 'Variable $number is even' } else { say 'Variable $number is odd' } 4.6. Chained Conditionals 55 If the remainder when $number is divided by 2 is 0, then we know that $number is even, and the program displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution. Note that if $number is evenly divisible by two, this code will print: Variable $number is even The $number variable value is not interpolated, because we used single quotes for the purpose of printing out the variable name rather than its value. We would have to use double quotes if we wanted to display the variables value instead of its name. 4.6 Chained Conditionals Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional: if $x < $y { say 'Variable $x is less than variable $y' } elsif $x > $y { say 'Variable $x is greater than variable $y' } else { say 'Variables $x and $y are equal' } The elsif keyword is an abbreviation of else if that has the advantage of avoiding nesting of blocks. Again, exactly one branch will run. There is no limit on the number of elsif statements. If there is an else clause, it has to be at the end, but there doesnt have to be one: if $choice eq 'a' { draw_a() } elsif $choice eq 'b' { draw_b() } elsif $choice eq 'c' { draw_c() } Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs. 4.7 Nested Conditionals One conditional can also be nested within another. We could have written the example in the previous section like this: 56 Chapter 4. Loops, Conditionals, and Recursion if $x == $y { say 'Variables $x and $y are equal' } else { if $x < $y { say 'Variable $x is less than variable $y' } else { say 'Variable $x is greater than variable $y' } } The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well. The if $x < $y conditional is said to be nested within the else branch of the outer conditional. Such nested conditionals show how critical it is for your own comprehension to properly indent conditional statements, as it would be very difficult here to visually grasp the structure without the help of correct indentation. Although the indentation of the statements helps make the structure apparent, nested conditionals become difficult to read very quickly. It is a good idea to avoid them when you can. Logical operators often provide a way to simplify nested conditional statements. For example, consider the following code (which assumes $x to be an integer): my Int $x; # ... $x = ...; if 0 < $x { if $x < 10 { say 'Value of $x is a positive single-digit number.' } } The say statement runs only if we make it past both conditionals, so we can get the same effect with the and Boolean operator, and the code can be rewritten using a single conditional: if 0 < $x and $x < 10 { say '$x is a positive single-digit number.' } For this kind of condition, Raku provides a more concise option using the chained relational operators described earlier: if 0 < $x < 10 { say '$x is a positive single-digit number.' } 4.8 If Conditionals as Statement Modifiers There is also a form of if called a statement modifier (or sometimes postfix conditional) form when there is only one conditional statement. In this case, the if and the condition 4.9. Unless Conditional Statement 57 come after the code you want to run conditionally. Note that the condition is still always evaluated first: say '$number is negative.' if $number < 0; This is equivalent to: if $number < 0 { say '$number is negative.' } This syntactic form is more concise as it takes only one code line instead of three. The advantage is that you can see more of your program code on one screen, without having to scroll up and down. However, this syntax is neat and clean only when both the condition and the statement are short and simple, so it is probably best used only in these cases. The statement modifier form does not allow else and elsif statements. 4.9 Unless Conditional Statement If you dont like having to write negative conditions in a conditional if statement such as: if not $number >= 0 { say '$number is negative.' } you may write this instead: unless $number >= 0 { say '$number is negative.' } This unless keyword does exactly what the English says: it will display the sentence $number is negative. unless the number is greater than or equal to 0. You cannot use else or elsif statements with unless, because that would end up getting confusing. The unless conditional is most commonly used in its statement modifier (or postfix notation) form: say '$number is negative.' unless $number >= 0; 4.10 For Loops Suppose you need to compute and print the product of the first five positive digits (1 to 5). This product is known in mathematics as the factorial of 5 and is sometimes written as 5!. You could write this program: 58 Chapter 4. Loops, Conditionals, and Recursion my $product = 1 * 2 * 3 * 4 * 5; say $product; # prints 120 You could make it slightly simpler: say 2 * 3 * 4 * 5; # prints 120 The problem is that this syntactic construct does not scale well and becomes tedious for the product of the first ten integers (or factorial 10). And it becomes almost a nightmare for factorial 100. Calculating the factorial of a number is a fairly common computation in mathematics (especially in the fields of combinatorics and probability) and in computer science. We need to automatize it, and using a for loop is one of the most obvious ways of doing that: my $product = 1; for 1..5 { $product *= $_ } say $product; # prints 120 Now, if you need to compute factorial 100, you just need to replace the 5 in the code above with 100. Beware, though, the factorial function is known to grow extremely rapidly, and youll get a truly huge number, with 158 digits (i.e., a number much larger than the estimated total number of atoms in the known universe). In this script, 1..5 is the range operator, which is used here to generate a list of consecutive numbers between 1 and 5. The for keyword is used to iterate over that list, and $_ is a special variable that takes each successive value of this list: first 1, then 2, etc. until 5. In the code block forming the body of the loop, the $product variable is multiplied successively by each value of $_. The loop ends with 5 and the result, 120, is printed on the last line. This is a simple use of the for statement, but probably not the most commonly used in Raku; we will see more below. We will also see other types of loops. But that should be enough for now to let you write some loops. Loops are found everywhere in computer programming. The $_ special variable is known as the topical variable or simply the topic. It does not need to be declared and many syntactic constructs assign a value to it without explicitly mentioning it. Also, $_ is a implicit argument to methods called without an explicit invocant. For example, to print the first five integers, you might write: for 1..5 {.say}; # prints numbers 1 to 5, each on its line Here .say is a syntax shorthand equivalent to $_.say. And since, as we saw, $_ takes each successive value of the range introduced by the for keyword, this very short code line prints each number between 1 and 5, each on a different line. This is a typical example of the $_ topical variable being used without even being explicitly mentioned. We will see many other uses of the $_ special variable. Sometimes, you dont use the $_ loop variable within the loop, for example if you just want to do something five times but dont care each time through the loop at which iteration you have arrived. A subroutine that prints a message n times might look like this: 4.11. Recursion 59 sub print-n-times (Int $n, Str $message) { for 1..$n { say $message } } The for loop also has a statement modifier or postfix form, used here to compute again the factorial of 5: my $product = 1; $product *= $_ for 1..5; say $product; # prints 120 There is another syntax for the for loop, using an explicit loop variable: sub factorial (Int $num) { my $product = 1; for 1..$num -> $x { $product *= $x } return $product } say factorial 10; # 3628800 The for loop in this subroutine is using what is called a pointy block syntax. It is essentially the same idea as the previous for loops, except that, instead of using the $_ topical variable, we now declare an explicit $x loop variable with the 1..$num -> $x syntax to iterate over the range of values. Using an explicit loop variable can make your code clearer when things get more complicated, for example when you need to nest several for loops. We will see more examples of that later. We will also see several other ways of computing the factorial of a number in this book. 4.11 Recursion It is legal for one function or subroutine to call another; it is also legal for a subroutine to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do. For example, look at the following subroutine: sub countdown(Int $time-left) { if $time-left <= 0 { say 'Blastoff!'; } else { say $time-left; countdown($time-left - 1); } } If $n is 0 or negative, it outputs the word, Blastoff!. Otherwise, it outputs the value of $time-left and then calls a subroutine named countdownitselfpassing $n-1 as an argument. What happens if we call the subroutine like this? 60 Chapter 4. Loops, Conditionals, and Recursion countdown(3); The execution of countdown begins with $time-left = 3, and since $time-left is greater than 0, it outputs the value 3, and then calls itself... The execution of countdown begins with $time-left = 2, and since $time-left is greater than 0, it outputs the value 2, and then calls itself... The execution of countdown begins with $time-left = 1, and since $time-left is greater than 0, it outputs the value 1, and then calls itself... The execution of countdown begins with $time-left = 0, and since $time-left is not greater than 0, it outputs the word, Blastoff! and then returns. The countdown that got $time-left = 1 returns. The countdown that got $time-left = 2 returns. The countdown that got $time-left = 3 returns. And then youre back in the main program. So, the total output looks like this: 3 2 1 Blastoff! A subroutine that calls itself is recursive; the process of executing it is called recursion. As another example, we can write a subroutine that prints a string $n times: sub print-n-times(Str $sentence, Int $n) { return if $n <= 0; say $sentence; print-n-times($sentence, $n - 1); } If $n <= 0, the return statement exits the subroutine. The flow of execution immediately returns to the caller, and the remaining lines of the subroutine dont run. This illustrates a feature of the return statement that we have not seen before: it is used here for flow control, i.e., to stop the execution of the subroutine and pass control back to the caller. Note also that, here, the return statement does not return any value to the caller; print-n-times is a void function. The rest of the subroutine is similar to countdown: it displays $sentence and then calls itself to display $sentence $n 1 additional times. So the number of lines of output is 1 + ($n - 1), which adds up to $n. For simple examples like this, it may seem easier to use a for loop. But we will see examples later that are hard to write with a for loop and easy to write with recursion, so it is good to start early. 4.12. Stack Diagrams for Recursive Subroutines 61 Figure 4.1: Stack diagram. 4.12 Stack Diagrams for Recursive Subroutines In Section 3.10, we used a stack diagram to represent the state of a program during a subroutine call. The same kind of diagram can help interpret a recursive subroutine. Every time a subroutine gets called, Raku creates a frame to contain the subroutines local variables and parameters. For a recursive subroutine, there might be more than one frame on the stack at the same time. Figure 4.1 shows a stack diagram for countdown called with n = 3. As usual, the top of the stack is the frame for the main program. It is empty because we did not create any variables in it or pass any arguments to it. The four countdown frames have different values for the parameter $time-left. The bottom of the stack, where $time-left = 0, is called the base case. It does not make a recursive call, so there are no more frames. As an exercise, draw a stack diagram for print-n-times called with $sentence = 'Hello' and $n = 2. Then write a function called do-n-times that takes a function and a number, $num, as arguments, and that calls the given function $num times. Solution: see Section A.2 4.13 Infinite Recursion If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. This is known as infinite recursion, and it is generally not a good idea. In fact, your program will not actually execute forever but will die at some point when the computer runs out of memory or some other critical resource. You have to be careful when writing recursive subroutines. Make sure that you have a base case, and make sure that you are guaranteed to reach it. Actually, although this is not absolutely required by the language, I would advise you to take the good habit of treating the base case first. 62 Chapter 4. Loops, Conditionals, and Recursion 4.14 Keyboard Input The programs we have written so far accept no input from the user. They just do the same thing every time. Raku provides built-in functions that stop the program and wait for the user to type something. For example, the prompt function prompts the user with a question or an instruction. When the user presses Return or Enter, the program resumes and prompt returns what the user typed as a string (without the newline character corresponding to the Return key typed by the user): my $user = prompt "Please type in your name: "; say "Hello $user"; This is probably one of the most common ways to obtain interactive user input, because it is usually a good idea to tell the user what is expected. Another possibility is to use the get method (which reads a single line) on standard input: say "Please type in your name: "; my $user = $*IN.get; say "Hello $user"; or the get function, which reads a line from standard input by default: say "Please type in your name: "; my $user = get; say "Hello $user"; 4.15 Program Arguments and the MAIN Subroutine There is another (and often better) way to have a program use varying input defined by the user, which is to pass command-line arguments to the program, just as we have passed arguments to our subroutines. The easiest way to retrieve arguments passed to a program is to use a special subroutine named MAIN. A program that has a defined MAIN subroutine will call automatically that subroutine and the command-line arguments supplied to the program will be passed as arguments to MAIN. The MAIN signature will enable you to retrieve the arguments provided in the command line and possibly also check their validity. For example, the greet.raku program might look like this: sub MAIN (Str $name) { say "Hello $name"; } You may call this program twice with different command-line arguments as follows: 4.16. Debugging 63 $ raku greet.raku Larry Hello Larry $ raku greet.raku world Hello world It is very easy to change the argument, since all you need to do at the operating system command line is use the up arrow and edit the end of the previous command line. If you forget to supply the argument (or provide the wrong number of arguments, or arguments not matching the signature), the program will die and Raku will nicely generate and display a usage method: $ raku greet.raku Usage: greet.raku 4.16 Debugging When a syntax or runtime error occurs, the error message contains a lot of information, but it can be overwhelming. The most useful parts are usually: What kind of error it was Where it occurred Syntax errors are usually easy to find, but there are a few gotchas. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code, sometimes on a previous line or even many lines before. For example, the goal of the following code was to display the multiplication tables: # WARNING: faulty code sub multiplication-tables { for 1..10 -> $x { for 1..10 -> $y { say "$x x $y\t= ", $x * $y; say ""; } } multiplication-tables(); It failed at compilation with the following error: $ raku mult_table.raku ===SORRY!=== Error while compiling /home/Laurent/mult_table.raku Missing block (taken by some undeclared routine?) at /home/Laurent/mult_table.raku:9 ------> multiplication-tables(); 64 Chapter 4. Loops, Conditionals, and Recursion The error message reports an error on line 9 of the program (the last line of the code), at the end of the line, but the actual error is a missing closing brace after line 4 and before line 5. The reason for this is that, while the programmer made the mistake on line 4, the Raku interpreter could not detect this error before it reached the end of the program. The correct program for displaying multiplication tables might be: sub multiplication-tables { for 1..10 -> $x { for 1..10 -> $y { say "$x x $y\t= ", $x * $y; } say ""; } } multiplication-tables(); When an error is reported on the last line of a program, it is quite commonly due to a missing closing parenthesis, bracket, brace, or quotation mark several lines earlier. An editor with syntax highlighting can sometimes help you. The same is true of runtime errors. Consider this program aimed at computing 360 degrees divided successively by the integers between 2 and 5: # WARNING: faulty code my ($a, $b, $c, $d) = 2, 3, 5; my $value = 360; $value /= $_ for $a, $b, $c, $d; say $value; This programs compiles correctly but displays a warning and then an exception on runtime: Use of uninitialized value of type Any in numeric context in block at product.raku line 3 Attempt to divide 12 by zero using div in block at product.raku line 4 The error message indicates a division by zero exception on line 4, but there is nothing wrong with that line. The warning on line 3 might give us a clue that the script attempts to use an undefined value, but the real error is on the first line of the script, where one of the four necessary integers (4) was omitted by mistake from the list assignment. You should take the time to read error messages carefully, but dont assume they point to the root cause of the exception; they often point to subsequent problems. 4.17 Glossary Integer division An operation, denoted div, that divides two numbers and rounds down (toward zero) the result to an integer. Modulo operator An operator, denoted with a percent sign (%), that works on integers and returns the remainder when one number is divided by another. 4.18. Exercises 65 Boolean expression An expression whose value is either True or False. Relational operator One of the operators that compares its operands. The most common numeric relational operators are ==, !=, >, <, >=, and <=. The equivalent string relational operators are eq, ne, gt, lt, ge, and le. Logical operator One of the operators that combines Boolean expressions: and, or, and not. The equivalent higher-precedence operators are &&, ||, and ! Conditional statement A statement that controls the flow of execution depending on some condition. Condition The boolean expression in a conditional statement that determines which branch runs. Branch One of the alternative sequences of statements in a conditional statement. Chained conditional A conditional statement with a series of alternative branches. Nested conditional A conditional statement that appears in one of the branches of another conditional statement. Statement modifier A postfix conditional expression, i.e., a conditional expression (using for example if, unless or for) that is placed after the statement the executions of which it controls. It can also refer to a postfix looping expression. Return statement A statement that causes a function to end immediately and return to the caller. Recursion The process of calling the function that is currently executing. Base case A conditional branch in a recursive function that does not make a recursive call. Infinite recursion A recursion that doesnt have a base case, or never reaches it. Eventually, an infinite recursion causes a runtime error, for which you may not want to wait because it may take a long time. 4.18 Exercises Exercise 4.1. Using the integer division and the modulo operators: 1. Write a subroutine that computes how many days, hours, minutes and seconds there are in the number of seconds passed as an argument to the subroutine. 2. Write a script that computes how many days, hours, minutes and seconds there are in 240,000 seconds. 3. Change your script to compute the number of days, hours, minutes and seconds there are in a number of seconds entered by the script user when prompted to give a number of seconds. Solutions: Subsection A.2.2. 66 Chapter 4. Loops, Conditionals, and Recursion Exercise 4.2. Fermats Last Theorem says that there are no positive integers a, b, and c such that an + bn = cn for any values of n greater than 2. 1. Write a function named check-fermat that takes four parametersa, b, c, and nand checks to see if Fermats theorem holds. If n is greater than 2 and an + bn = cn the program should print, Holy smokes, Fermat was wrong! Otherwise the program should print, No, that doesnt work. 2. Write a function that prompts the user to input values for a, b, c, and n, converts them to integers, and uses check-fermat to check whether they violate Fermats theorem. Solution: A.2.3 Exercise 4.3. If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle: If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can. (If the sum of two lengths equals the third, they form what is called a degenerate triangle.) 1. Write a function named is-triangle that takes three positive numbers as arguments, and that prints either Yes or No, depending on whether you can form a triangle from sticks with the given lengths. 2. Write a function that prompts the user to input three stick lengths and uses is-triangle to check whether sticks with the given lengths can form a triangle. Solution: A.2.4 Exercise 4.4. The Fibonacci numbers were invented by Leonardo Fibonacci (a.k.a. Leonardo of Pisa or simply Fibonacci), an Italian mathematician of the thirteenth century. The Fibonacci numbers are a sequence of numbers such as: 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . in which the first two numbers are equal to 1 and each subsequent number of the sequence is defined as the sum of the previous two (for example, 5 = 2 + 3, 8 = 3 + 5, etc.). In mathematical notation, the Fibonacci numbers could be defined by recurrence as follows: F1 = 1, F2 = 1, and Fn = Fn1 + Fn2 1. Write a program using a for loop that prints on screen the first 20 Fibonacci numbers. 4.18. Exercises 67 2. Write a program which prompts the user to enter a number n and, using a for loop, computes and displays the nth Fibonacci number. Solution: A.2.5 Exercise 4.5. What is the output of the following program? Draw a stack diagram that shows the state of the program when it prints the result. sub recurse($n, $s) { if ($n == 0) { say $s; } else { recurse $n - 1, $n + $s; } } recurse 3, 0; 1. What would happen if you called the function like this: recurse(-1, 0)? 2. Write a documentation comment (maybe in the form of a multiline comment) that explains everything someone would need to know in order to use this function (and nothing else). Solution: A.2.6 68 Chapter 4. Loops, Conditionals, and Recursion Chapter 5 Fruitful Subroutines Most of the Raku functions we have used, such as the math functions, produce return values. But most of the subroutines weve written so far are void: they have an effect, like printing a value, but they dont have a return value. In this chapter you will learn to write fruitful functions. 5.1 Return Values Calling a fruitful function generates a return value, which we usually assign to a variable or use as part of an expression: my $pi = 4 * atan 1; my $height = $radius * sin $radians; Many of the subroutines we have written so far are void. Speaking casually, they have no usable return value; more precisely, their return value may be Any, Nil, (), or True. In this chapter, we are (finally) going to write fruitful subroutines. The first example is area, which returns the area of a circle with the given radius: sub area($radius) { my $circular_area = pi * $radius**2; return $circular_area; } We have seen the return statement before, but in a fruitful function the return statement includes an expression. This statement means: Return immediately from this function and use the following expression as a return value. The expression can be arbitrarily complicated, so we could have written this function more concisely: sub area($radius) { return pi * $radius**2; } 70 Chapter 5. Fruitful Subroutines On the other hand, temporary variables like $circular_area can make debugging easier. They may also help document what is going on. Sometimes it is useful to have multiple return statements, for example one in each branch of a conditional: sub absolute_value($num){ if $num < 0 { return -$num; } else { return $num; } } Since these return statements are in an alternative conditional, only one runs. This could also be written more concisely using the statement modifier syntax: sub absolute_value($num){ return -$num if $num < 0; return $num; } Here again, only one of the return statements runs: if the number is negative, the first return statement is executed and the subroutine execution stops there; if the number is positive or zero, then only the second return statement is executed. As soon as a return statement runs, the function terminates without executing any subsequent statements. Code that appears after an unconditional return statement, or any other place the flow of execution can never reach, is called dead code. In a fruitful function, it is a good idea to ensure that every possible path through the program hits a return statement. For example: # WARNING: faulty code sub absolute_value($num){ if $num < 0 { return -$num; } if $num > 0 { return $num; } } This subroutine is incorrect because if $num happens to be 0, neither condition is true, and the subroutine ends without hitting a return statement. If the flow of execution gets to the end of a function, the return value is (), which basically means not defined and is clearly not the absolute value of 0: > absolute_value(0) () By the way, Raku provides a built-in function called abs that computes absolute values. As an exercise, write a compare subroutine that takes two numbers, $x and $y, and returns 1 if $x > $y, 0 if $x == $y, and -1 if $x < $y. Solution: A.3.1 5.2. Incremental Development 5.2 71 Incremental Development As you write larger functions, you might find yourself spending more time debugging. To deal with increasingly complex programs, you might want to try a process called incremental development. The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time. As an example, suppose you want to find the distance between two points, given by the Cartesian or rectangular coordinates ( x1 , y1 ) and ( x2 , y2 ). By the Pythagorean theorem, the distance is: distance = q ( x2 x1 )2 + ( y2 y1 )2 The first step is to consider what a distance function should look like in Raku. In other words, what are the inputs (parameters) and what is the output (return value)? In this case, the inputs are two points, which you can represent using four numbers. The return value is the distance represented by a numeric value. Immediately you can write an outline of the function: sub distance($x1, $y1, $x2, $y2) { return 0.0; } Obviously, this version doesnt compute distances; it always returns zero. But it is syntactically correct, and it runs, which means that you can test it before you make it more complicated. To test the new function, call it with sample arguments: > distance(1, 2, 4, 6); 0.0 I chose these values so that the horizontal distance is 3 and the vertical distance is 4; that way, the result is 5, the hypotenuse of a 3-4-5 triangle. When testing a function, it is useful to know the right answer. At this point we have confirmed that the function is syntactically correct, and we can start adding code to the body. A reasonable next step is to find the differences x2 x1 and y2 y1 . The next version stores those values in temporary variables and prints them: sub distance($x1, $y1, $x2, $y2) { my $dx = $x2 - $x1; my $dy = $y2 - $y1; say '$dx is', $dx; say '$dy is', $dy; return 0.0; } If the function is working, it should display $dx is 3 and $dy is 4 (and still return 0.0). If so, we know that the function is getting the right arguments and performing the first computation correctly. If not, there are only a few lines to check. Next we compute the sum of squares of $dx and $dy: 72 Chapter 5. Fruitful Subroutines sub distance($x1, $y1, $x2, $y2) { my $dx = $x2 - $x1; my $dy = $y2 - $y1; my $dsquared = $dx**2 + $dy**2; say '$dsquared is: ', $dsquared; return 0.0; } Again, you would run the program at this stage and check the output (which should be 25). Finally, you can use the sqrt built-in function to compute and return the result: sub distance($x1, $y1, $x2, $y2) { my $dx = $x2 - $x1; my $dy = $y2 - $y1; my $dsquared = $dx**2 + $dy**2; my $result = sqrt $dsquared; return $result; } If that works correctly, you are done. Otherwise, you might want to print the value of $result before the return statement. The final version of the subroutine doesnt display anything when it runs; it only returns a value. The print statements we wrote are useful for debugging, but once you get the function working, you should remove them. Code like that is sometimes called scaffolding because it is helpful for building the program but is not part of the final product. When you start programming, you should add only a line or two of code at a time. As you gain more experience, you might find yourself writing and debugging bigger chunks. Either way, incremental development can save you a lot of debugging time. The key aspects of the process are: 1. Start with a working program and make small incremental changes. At any point, if there is an error, you should have a good idea where it is. 2. Use variables to hold intermediate values so you can display and check them. 3. Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions, but only if doing so does not make the program difficult to read. Note that, at least for relatively simple cases, you can also use the REPL to test expressions and even multiline statements or subroutines in interactive mode before you commit them to your program code. This is usually fast and can save you some time. As an exercise, use incremental development to write a function called hypotenuse that returns the length of the hypotenuse of a right triangle given the lengths of the other two legs as arguments. Record each stage of the development process as you go. Solution: A.3.2. 5.3. Composition 5.3 73 Composition As you should expect by now, you can call one function from within another. As an example, well write a function that takes two points, the center of the circle and a point on the perimeter, and computes the area of the circle. Assume that the center point is stored in the variables $x-c and $y-c, and the perimeter point is in $x-p and $y-p. The first step is to find the radius of the circle, which is the distance between the two points. We just wrote a function, distance, that does that: my $radius = distance($x-c, $y-c, $x-p, $y-p); The next step is to find the area of a circle with that radius; we just wrote that, too: my $result = area($radius); Encapsulating these steps in a function, we get: sub circle-area($x-c, $y-c, $x-p, $y-p) { my $radius = distance($x-c, $y-c, $x-p, $y-p); my $result = area($radius); return $result; } The temporary variables $radius and $result are useful for development and debugging, but once the program is working, we can make it more concise by composing the function calls: sub circle-area($x-c, $y-c, $x-p, $y-p) { return area distance($x-c, $y-c, $x-p, $y-p); } The last line of the previous example now works like a data pipeline from right to left: the distance function takes the four arguments and returns a distance (the radius) which is fed as an argument to the area; with this argument, area is now able to return the area, which is then returned by circle-area to the caller code. Well come back later to this very expressive data pipeline model. 5.4 Boolean Functions Functions can return Boolean values, which is often convenient for hiding complicated tests inside functions. For example: sub is-divisible(Int $x, Int $y) { if $x % $y == 0 { return True; } else { return False; } } 74 Chapter 5. Fruitful Subroutines It is common to give Boolean functions names that sound like yes/no questions; is-divisible, for instance, returns either True or False to indicate whether x is divisible by y. Here is an example: > is-divisible(6, 4); False > is-divisible(6, 3); True The result of the == operator is a Boolean value, so we can write the subroutine more concisely by returning it directly: sub is-divisible(Int $x, Int $y) { return $x % $y == 0 } If there is no return statement, a Raku subroutine returns the value of expression on the last code line of the subroutine (provided the last code line is an expression that gets evaluated), so that the return statement is not required here. In addition, since 0 is a false value and any other integer a true value, this could be further rewritten as follows: sub is-divisible(Int $x, Int $y) { not $x % $y } The Int type declarations in the subroutine signatures above are not necessary. The subroutine would work without them, but they can provide some form of protection against using this subroutine with faulty arguments. Boolean functions are often used in statement modifiers: say "$x is divisible by $y" if is-divisible($x, $y); It might be tempting to write something like: say "$x is divisible by $y" if is-divisible($x, $y) == True; But the extra comparison is unnecessary: is-divisible returns a Boolean value that can be interpreted directly by the if conditional. As an exercise, write a function is-between(x, y, z) that returns True if x y z or False otherwise. Solution: A.3.3. 5.5. A Complete Programming Language 5.5 75 A Complete Programming Language Weve seen in the section above several ways of writing a subroutine to check the divisibility of two integers. In fact, as briefly mentioned earlier, Raku has a is divisible operator, %%, which returns True if the number on the left is divisible by the one on the right: > 9 %% 3 True > 9 %% 4 False So there was no need to write the is-divisible subroutine. But dont worry, thats all right if you did not remember that. Speakers of natural languages are allowed to have different skill levels, to learn as they go and to put the language to good use before they know the whole language. The same is true with Raku. You (and I) dont know all about Raku yet, just as we dont know all of English. But it is in fact Officially Okay in the Perl and Raku Culture to use the subset of the language that you know. You are in fact encouraged to use what is sometimes called baby Perl or baby Raku to write programs, even if they are somewhat clumsy at the beginning. Thats the best way of learning Raku, just as using baby talk is the right way for a child to learn English. The number of different ways of accomplishing a given task, such as checking whether one number is divisible by another, is an example of one of Perls and Rakus mottos: there is more than one way to do it, oft abbreviated TIMTOWTDI. Some ways may be more concise or more efficient than others, but, in the Perl and Raku philosophy, you are perfectly entitled to do it your way, especially if youre a beginner, provided you find the correct result. We have only covered a small subset of Raku so far, but you might be interested to know that this subset is a complete programming language, which means that essentially anything that can be computed can be expressed in this language. Any program ever written could be rewritten using only the language features you have learned so far (actually, you would need a few commands to control devices like the mouse, disks, networks, etc., but thats all). Proving that claim is a nontrivial exercise first accomplished by Alan Turing, one of the first computer scientists (some would argue that he was a mathematician, but a lot of early computer scientists started as mathematicians). Accordingly, it is known as the Turing Thesis. For a more complete (and accurate) discussion of the Turing Thesis, I recommend Michael Sipsers book Introduction to the Theory of Computation. 5.6 More Recursion To give you an idea of what you can do with the tools you have learned so far, well evaluate a few recursively defined mathematical functions. A recursive definition is similar to a circular definition, in the sense that the definition contains a reference to the thing being defined. A truly circular definition is not very useful: Vorpal An adjective used to describe something that is vorpal. 76 Chapter 5. Fruitful Subroutines If you saw that definition in the dictionary, you might be annoyed. On the other hand, if you looked up the definition of the factorial function, denoted with the symbol !, you might get something like this: 0! = 1 n! = n(n 1)! This definition says that the factorial of 0 is 1, and the factorial of any other (positive integer) value, n, is n multiplied by the factorial of n 1. So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together, 3! equals 3 times 2 times 1 times 1, which is 6. If you can write a recursive definition of something, you can write a Raku program to evaluate it. The first step is to decide what the parameters should be. In this case it should be clear that factorial takes a number1 : sub factorial($n){ } If the argument happens to be 0, all we have to do is return 1: sub factorial($n){ if $n == 0 { return 1; } } Otherwise, and this is the interesting part, we have to make a recursive call to find the factorial of n 1 and then multiply it by n: sub factorial($n){ if $n == 0 { return 1; } else { my $recurse = factorial($n-1); my $result = $n * $recurse; return $result; } } The flow of execution for this program is similar to the flow of countdown in Section 4.11. If we call factorial with the value 3: Since 3 is not 0, we take the second branch and calculate the factorial of $n-1... Since 2 is not 0, we take the second branch and calculate the factorial of $n-1... Since 1 is not 0, we take the second branch and calculate the factorial of $n-1... Since 0 equals 0, we take the first branch and return 1 without making any more recursive calls. 1 It should really be an integer, but well get back to that later in this chapter. 5.7. Leap of Faith 77 __main__ 6 factorial n 3 recurse 2 result 6 factorial n 2 recurse 1 result 2 factorial n 1 recurse 1 result 1 factorial n 0 2 1 1 Figure 5.1: Stack diagram. The return value, 1, is multiplied by $n, which is 1, and the result is returned. The return value, 1, is multiplied by $n, which is 2, and the result is returned. The return value, 2, is multiplied by $n, which is 3, and the result, 6, becomes the return value of the subroutine call that started the whole process. Figure 5.1 shows what the stack diagram looks like for this sequence of function calls. The return values are shown being passed back up the stack. In each frame, the return value is the value of result, which is the product of n and recurse. In the last frame, the local variables recurse and result do not exist, because the branch that creates them does not run. A seasoned Raku programmer might write a more concise or more idiomatic subroutine2 : sub factorial($n){ return 1 if $n == 0; return $n * factorial $n-1; } This is not better than our initial version, and will probably not run significantly faster, but this is arguably clearer, at least once you get used to this type of syntax. 5.7 Leap of Faith Following the flow of execution is one way to read programs, but it can quickly become overwhelming. An alternative is what may be called the leap of faith. When you come to a subroutine call, instead of following the flow of execution, you assume that the subroutine works correctly and returns the right result. In fact, you are already practicing this leap of faith when you use built-in functions. When you call math functions such as cos or sqrt, you dont examine the bodies of those functions. You just assume that they work because the people who wrote the built-in functions 2 We will see later even more idiomatic ways of computing the factorial of a number. 78 Chapter 5. Fruitful Subroutines were likely to be good programmers (and because you can safely assume that they have been thoroughly tested). The same is true when you call one of your own subroutines. For example, in Section 5.4, we wrote a subroutine called is-divisible that determines whether one number is divisible by another. Once we have convinced ourselves that this subroutine is correctby examining the code and testingwe can use the subroutine without looking at the body again. The same is true of recursive programs. When you get to the recursive call, instead of following the flow of execution, you should assume that the recursive call works (returns the correct result) and then ask yourself, Assuming that I can find the factorial of $n-1, can I compute the factorial of $n? It is clear that you can, by multiplying by $n. Of course, its a bit strange to assume that the subroutine works correctly when you havent finished writing it, but thats why its called a leap of faith! 5.8 One More Example After factorial, the most common example of a recursively defined mathematical function is fibonacci, which has the following definition (see http://en.wikipedia.org/ wiki/Fibonacci_number): fibonacci(0) = 1 fibonacci(1) = 1 fibonacci(n) = fibonacci(n 1) + fibonacci(n 2) In plain English, a Fibonacci sequence is a sequence of numbers such as: 1, 1, 2, 3, 5, 8, 13, 21, ... where the two first terms are equal to 1 and any other term is the sum of the two preceding ones. We briefly covered the Fibonacci sequence in Exercise 4.4 of the previous chapter and implemented it with a for loop. Lets now translate the recursive definition into Raku. It looks like this: sub fibonacci ($n) { return 1 if $n == 0 or $n == 1; return fibonacci($n-1) + fibonacci($n-2) } If you try to follow the flow of execution here, even for fairly small values of $n, your head explodes. But according to the leap of faith, if you assume that the two recursive calls work correctly, then it is clear that you get the right result by adding them together. 5.9. Checking Types 5.9 79 Checking Types What happens if we call factorial and give it 1.5 as an argument? It seems that we get an infinite recursion. How can that be? The subroutine has a base casewhen $n == 0. But if $n is not an integer, we can miss the base case and recurse forever. In the first recursive call, the value of $n is 0.5. In the next, it is -0.5. From there, it gets smaller (more negative), but it will never be 0. We have two choices. We can try to generalize the factorial function to work with noninteger numbers, or we can make factorial check its argument. The first option is called the gamma function and its a little beyond the scope of this book. So well go for the second. We have already seen examples of subroutines using the signature to verify the type of the argument. So we can add the Int type to the parameter in the signature. While were at it, we can also make sure the argument is positive or zero: sub factorial(Int $n where $n >= 0){ return 1 if $n == 0; return $n * factorial $n-1; } The Int type checking in the signature handles nonintegers, this is not new. The where $n >= 0 part is a parameter constraint: if the parameter is negative, the subroutine should fail. Technically, the constraint is implemented here within the signature using a syntax feature called a trait, that is a property imposed on the parameter at compile time. If the argument passed to the function is not an integer or if it is negative, the program prints an error message to indicate that something went wrong: > say factorial 1.5 Type check failed in binding $n; expected Int but got Rat in sub factorial at line 1 in block at line 1 > say factorial -3 Constraint type check failed for parameter '$n' > say factorial "Fred" Type check failed in binding $n; expected Int but got Str in sub factorial at line 1 in block at line 1 If we get past both checks, we know that $n is an integer and that it is positive or zero, so we can prove that the recursion terminates. Another way to achieve a similar result is to define your own subset of the built-in types. For example, you can create an Even-int subset of integers and then use it more or less as if it were a new type for declaring your variables or typing your subroutine parameters: subset Even-int of Int where { $_ %% 2 } # or : ... where { $_ % 2 == 0 } # Even-int can now be used as a type my Even-int $x = 2; # OK my Even-int $y = 3; # Type mismatch error 80 Chapter 5. Fruitful Subroutines Similarly, in the case of the factorial subroutine, we can create a nonnegative integer subset and use it for checking the parameter passed to the subroutine: subset Non-neg-int of Int where { $_ >= 0} # ... sub factorial(Non-neg-int $n){ return 1 if $n == 0; return $n * factorial $n-1; } If we pass a negative integer to the subroutine, we get a similar error as before: Constraint type check failed for parameter '$n'... This program demonstrates a pattern sometimes called a guardian. The signature acts as a guardian, protecting the code that follows from values that might cause an error. The guardians make it possible to prove the correctness of the code. 5.10 Multi Subroutines It is possible to write multiple versions of a subroutine with the same name but with different signatures, for example a different arity (a fancy word for the number of arguments) or different argument types, using the multi keyword. In this case, the interpreter will pick the version of the subroutine whose signature matches (or best matches) the argument list. This process is called dispatch. Dispatch happens depending on the number (arity), type and name of arguments. For example, we could rewrite the factorial function as follows: multi sub fact(0) { 1 }; multi sub fact(Int $n where $n > 0) { $n * fact $n - 1; } say fact 0; # -> 1 say fact 10; # -> 3628800 Here, we dont enter into infinite recursion because, when the parameter passed to fact is 0, it is the first version of the multi subroutine that is called and it returns an integer value (1), and this ends the recursion. Similarly, the Fibonacci function can be rewritten with multi subroutines: multi fibonacci(0) { 1 } multi fibonacci(1) { 1 } multi fibonacci(Int $n where $n > 1) { fibonacci($n - 2) + fibonacci($n - 1) } say fibonacci 10; # -> 89 5.11. Debugging 81 Note that in the fibonacci example just above, we have omitted the sub keyword, since it isnt necessary after the multi declarator. Many built-in functions and most operators of Raku are written as multi subroutines. In the two examples above, only one of the multi subroutine signature could match the input parameters. For example, if the argument passed to the fact subroutine is 0, then the first version is called; if the argument is greater than 0, then the second version is called. What if more that one signature matches the passed arguments? Then, the dispatch process becomes a little bit more complicated. As said at the beginning of this section, the runtime environment will select the candidate subroutine that best matches the signature. In such cases, the run time environment first looks at the arity (number of arguments) of the signature. If only one signature matches the number of parameters passed to the subroutine, then it is this candidate subroutine that is selected. If, on the other hand, several signatures match the number of arguments, then the type of the arguments drives the dispatch. 3 5.11 Debugging Breaking a large program into smaller functions or subroutines creates natural checkpoints for debugging. If a subroutine is not working, there are three possibilities to consider: There is something wrong with the arguments the subroutine is getting; a precondition is violated. There is something wrong with the subroutine; a postcondition is violated. There is something wrong with the return value or the way it is being used. To rule out the first possibility, you can add a print statement at the beginning of the function and display the values of the parameters (and maybe their types). Or you can write code that checks the preconditions explicitly. For the purpose of debugging, it is often useful to print the content of a variable or of a parameter within a string with surrounding characters, so that you may visualize characters that are otherwise invisible, such as spaces or newlines. For example, you think that the $var should contain two, and run the following test: if $var eq "two" { do-something() } But it fails and the do-something subroutine is never called. Perhaps you want to use a print statement that will ascertain the content of $var: say "[$var]"; if $var eq "two" { do-something() } 3 We will see later (see section 11.4.1) that there can be other types of signatures, with named parameters. Lets just say here that, when there are named arguments, they drive the dispatch even when their type is the same as another candidate. 82 Chapter 5. Fruitful Subroutines This might print: [two ] or: [two ] Now, you know that the equality test fails because $var contains a trailing character (space or newline) that might otherwise be difficult to detect. If the parameters look good, add a print statement before each return statement and display the return value. If possible, check the result by hand. Consider calling the function with values that make it easy to check the result (as in Section 5.2). If the function seems to be working, look at the function call to make sure the return value is being used correctly (or used at all!). Adding print statements at the beginning and end of a function can help make the flow of execution more visible. For example, here is a version of factorial with print statements: sub factorial(Int $n) { my $space = ' ' x (4 * $n); say $space, 'factorial ', $n; if $n == 0 { say $space, 'returning 1'; return 1; } else { my $result = $n * factorial $n-1; say $space, 'returning ', $result; return $result; } } The $space variable is a string of space characters that controls the indentation of the output. Here is the result of factorial(4) : factorial 4 factorial 3 factorial 2 factorial 1 factorial 0 returning 1 returning 1 returning 2 returning 6 returning 24 If you are confused about the flow of execution, this kind of output can be helpful. It takes some time to develop effective scaffolding, but a bit of scaffolding can save a lot of debugging. 5.12. Glossary 5.12 83 Glossary Temporary variable A variable used to store an intermediate value in a complex calculation. Dead code Part of a program that can never run, often because it appears after a return statement. Incremental development A program development plan intended to avoid debugging by adding and testing only a small amount of code at a time. Scaffolding Code that is used during program development but is not part of the final version. Guardian A programming pattern that uses a conditional statement to check for and handle circumstances that might cause an error. 5.13 Exercises Exercise 5.1. Draw a stack diagram for the following program. What does the program print? Please try to answer these questions before trying to run the program. sub b(Int $z) { my $prod = a($z, $z); say $z, " ", $prod; return $prod; } sub a(Int $x is copy, Int $y) { $x++; return $x * $y; } sub c(Int $x, Int $y, Int $z) { my $total = $x + $y + $z; my $square = b($total) ** 2; return $square; } my $x = 1; my $y = $x + 1; say c($x, $y + 3, $x + $y); Exercise 5.2. The Ackermann function, A(m, n), is defined as follows: n + 1 A(m, n) = A(m 1, 1) A(m 1, A(m, n 1)) if m = 0 if m > 0 and n = 0 if m > 0 and n > 0. See http: // en. wikipedia. org/ wiki/ Ackermann_ function . Write a subroutine named ack that evaluates the Ackermann function. Use your subroutine to evaluate ack(3, 4), which should be 125. What happens for larger values of m and n? Solution: A.3.4. 84 Chapter 5. Fruitful Subroutines Exercise 5.3. A palindrome is a word that is spelled the same backward and forward, like noon and redivider. Recursively, a word is a palindrome if the first and last letters are the same and the middle is a palindrome. The following are subroutines that take a string argument and return the first, last, and middle letters: sub first_letter(Str $word){ return substr $word, 0, 1; } sub last_letter(Str $word){ return substr $word, *-1, 1; } sub middle_letter(Str $word){ return substr $word, 1, *-1; } Dont worry about how they work for the time being; we will see that in Chapter 7 on strings. For now: 1. Type these subroutines into a file named palindrome.raku and test them out. What happens if you call middle_l with a string with two letters? One letter? What about the empty string, which is written '' and contains no letters? Given that the .chars method returns the length of a string, how could you add a signature constraint to reject invalid input? 2. Write a subroutine called is-palindrome that takes a string argument and returns True if it is a palindrome and False otherwise. Remember that you can use the built-in method .chars to check the length of a string. Solution: A.3.5. Exercise 5.4. An integer number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is-power-of that takes parameters a and b and returns True if a is a power of b. Note: you will have to think about the base case. Solution: A.3.6 Exercise 5.5. The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder. One way to find the GCD of two numbers is based on the observation that if r is the remainder when a is divided by b, then gcd( a, b) = gcd(b, r ). As a base case, we can use gcd( a, 0) = a. Write a function called gcd that takes parameters a and b and returns their greatest common divisor. Credit: this exercise is based on an example from Abelson and Sussmans Structure and Interpretation of Computer Programs. Solution: A.3.7 Chapter 6 Iteration This chapter is about iteration, which is the ability to run a block of statements repeatedly. We saw a kind of iteration, using recursion, in Section 4.11. We saw another kind, using a for loop, in Section 4.10. In this chapter well see yet another kind, using a while statement. But first we want to say a little more about variable assignment. 6.1 Assignment Versus Equality Before going further, I want to address a common source of confusion. Because Raku uses the equals sign (=) for assignment, it is tempting to interpret a statement like $a = $b as a mathematical proposition of equality, that is, the claim that $a and $b are equal. But this interpretation is wrong. First, equality is a symmetric relationship and assignment is not. For example, in mathematics, if a = 7 then 7 = a. But in Raku, the statement $a = 7 is legal and 7 = $a is not. Also, in mathematics, a proposition of equality is either true or false for all time. If a = b now, then a will always equal b. In Raku, an assignment statement can make two variables equal, but they dont have to stay that way: > 5 > 5 > 3 > 5 my $a = 5; my $b = $a; # $a and $b are now equal $a = 3; # $a and $b are no longer equal say $b; The third line changes the value of $a but does not change the value of $b, so they are no longer equal. In brief, remember that = is an assignment operator and not an equality operator; the operators for testing equality between two terms are == for numbers and eq for strings. 86 Chapter 6. Iteration Figure 6.1: State diagram. 6.2 Reassignment As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the old value): > 5 > 5 > 7 > 7 my $x = 5; say $x; $x = 7; say $x The first time we display $x, its value is 5; the second time, its value is 7. Figure 6.1 shows what reassignment looks like in a state diagram. Reassigning variables is often useful, but you should use this feature with some caution. If the values of variables change frequently, it can make the code difficult to read and debug. 6.3 Updating Variables A common kind of reassignment is an update, where the new value of the variable depends on the old: > $x = $x + 1; This means get the current value of $x, add one, and then update $x with the new value. If you try to update a variable that has not been given a value, you get a warning, because Raku evaluates the right side of the assignment statement before it assigns a value to $x: > my $x; > $x = $x + 1; Use of uninitialized value of type Any in numeric context in block at line 1 Before you can update a variable, you have to declare it and initialize it, usually with an assignment statement: 6.4. The while Statement 87 > my $x = 0; > $x = $x + 1; Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement. As mentioned earlier in Section 2.3, Raku has some shortcuts for increment and decrement : $x += 1; # equivalent to $x = $x + 1 $x++; # also equivalent $x -= 1; # equivalent to $x = $x - 1 $x--; # also equivalent 6.4 The while Statement Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. In a computer program, repetition is also called iteration. We have already seen two functions, countdown and print-n-times, that iterate using recursion (see Section 4.11). Because iteration is so common, most programming languages including Raku provide language features to make it easier. One is the for statement we saw in Section 4.10. Well get back to that later. Another is the while statement. Here is a version of countdown that uses a while statement: sub countdown(Int $n is copy) { while $n > 0 { say $n; $n--; } say 'Blastoff!'; } You can almost read the while statement as if it were English. It means, While $n is greater than 0, display the value of n and then decrement $n. When you get to 0, display the word Blastoff! More formally, here is the flow of execution for a while statement: 1. Determine whether the condition is true or false. 2. If false, exit the while statement and continue execution at the next statement. 3. If the condition is true, run the body and then go back to step 1. This type of flow is called a loop because the third step loops back around to the top. The body of the loop should change the value of one or more variables so that the condition becomes false eventually and the loop terminates. Otherwise, the loop will repeat forever, 88 Chapter 6. Iteration which is called an infinite loop. An endless source of amusement for computer scientists is the observation that the directions on shampoo, Lather, rinse, repeat, are an infinite loop. In the case of countdown, we can prove that the loop terminates: if $n is zero or negative, the loop never runs. Otherwise, $n gets smaller each time through the loop, so eventually we have to get to 0. For some other loops, it is not so easy to tell whether the loop terminates. For example: sub sequence($n is copy) { while $n != 1 { say $n; if $n %% 2 { # $n is even $n = $n / 2; } else { # $n is odd $n = $n*3 + 1 } } return $n; } The condition for this loop is $n != 1, so the loop will continue until $n is 1, which makes the condition false. Each time through the loop, the program outputs the value of $n and then checks whether it is even or odd. If it is even, $n is divided by 2. If it is odd, the value of $n is replaced with $n*3 + 1. For example, if the argument passed to sequence is 42, the resulting values of n are 42, 21, 64, 32, 16, 8, 4, 2, 1. Since $n sometimes increases and sometimes decreases, there is no obvious proof that $n will ever reach 1, or that the program terminates. For some particular values of n, we can prove termination. For example, if the starting value is a power of two, n will be even every time through the loop until it reaches 1. The previous example ends with such a sequence of powers of two, starting with 64. The hard question is whether we can prove that this program terminates for all positive values of n. So far, no one has been able to prove it or disprove it! (See http: //en.wikipedia.org/wiki/Collatz_conjecture.) As an exercise, you might want to rewrite the function print-n-times from Section 4.11 using iteration instead of recursion. The while statement can also be used as a statement modifier (or postfix syntax): my $val = 5; print "$val " while $val-- > 0; print "\n"; # prints 4 3 2 1 0 The while loop statement executes the block as long as its condition is true. There is also an until loop statement, which executes the block as long as its condition is false: my $val = 1; until $val > 5 { print $val++; } print "\n"; # prints 12345 6.5. Local Variables and Variable Scoping 6.5 89 Local Variables and Variable Scoping We have seen in Section 3.9 that variables created within a subroutine (with the my keyword) are local to that subroutine. The my keyword is often called a declarator, because it is used for declaring a new variable (or other identifier). It is by far the most common declarator. Other declarators include our or state, briefly described later in this chapter. Similarly, subroutine parameters are also usually local to the subroutine in the signature of which they are declared. We briefly mentioned that the term lexically scoped is probably more accurate than local, but it was too early at that point to really explain what this means. Declaring a variable with my gives it lexical scope. This means it only exists within the current block. Loosely speaking, a block is a piece of Raku code within curly brackets or braces. For example, the body of a subroutine and the code of a while or for loop or of an if conditional statement are code blocks. Any variable created with the my declarator exists and is available for use only between the place where it is declared and the end of the enclosing code block. For example, this code: if $condition eq True { my $foo = "bar"; say $foo; # prints "bar" } say $foo; # ERROR: "Variable '$foo' is not declared ..." will fail on the second print statement, because the say function call is not in the lexical scope of the $foo variable, which ends with the closing brace of the condition block. If we want this variable to be accessible after the end of the condition, then we would need to declare it before the if statement. For example: my $foo; if $condition eq True { $foo = "bar"; say $foo; # prints "bar" } else { $foo = "baz"; } say $foo; # prints "bar" or "baz" depending on $condition If a lexical variable is not declared within a block, its scope will extend until the end of the file (this is sometimes called a static or a global variable, although these terms are somewhat inaccurate). For example, in the last code snippet above, the scope of the $foo variable will extend until the end of the file, which may or may not be a good thing, depending on how you intend to use it. It is often better to reduce the scope of variables as much as possible, because this helps reduce dependencies between various parts of the code and limits the risk of subtle bugs. In the code above, if we want to limit the scope of $foo, we could add braces to create an enclosing block for the sole purpose of limiting the scope: { my $foo; 90 Chapter 6. Iteration } if $condition eq True { $foo = "bar"; say $foo; # prints "bar" } else { $foo = "baz"; } say $foo; # prints "bar" or "baz" depending on $condition Now, the outer braces create an enclosing block limiting the scope of $foo to where we need it. This may seem to be a somewhat contrived example, but it is not uncommon to add braces only for the purpose of precisely defining the scope of something. Lexical scoping also means that variables with the same names can be temporarily redefined in a new scope: my $location = "outside"; sub outer { say $location; } sub inner { my $location = "inside"; say $location; } say $location; # -> outside outer(); # -> outside inner(); # -> inside say $location; # -> outside We have in effect two variables with the same name, $location, but different scopes. One is valid only within the inner subroutine where it has been redefined, and the other anywhere else. If we add a new subroutine: sub nowhere { my $location = "nowhere"; outer(); } nowhere(); # -> outside this will still print outside, because the outer subroutine knows about the outside version of the $location variable, which existed when outer was defined. In other word, the outer code that referenced to the outer variable (outside) knows about the variable that existed when it was created, but not about the variable existing where it was called. This is how lexical variables work. This behavior is the basis for building closures, a form of subroutine with some special properties that we will study later in this book, but is in fact implicitly present everywhere in Raku. While having different variables with the same name can give you a lot of expressive power, we would advise you to avoid creating different variables with the same name 6.6. Control Flow Statements (last, next, etc.) 91 and different scopes, at least until you really understand these concepts well enough to know what you are doing, as this can be quite tricky. By far, most variables used in Raku are lexical variables, declared with the my declarator. Although they are not declared with my, parameters declared in the signature of subroutines and parameters of pointy blocks also have a lexical scope limited to the body of the subroutine or the code block. There are other declarators, such as our, which creates a package-scoped variable, and state, which creates a lexically scoped variable but with a persistent value. They are relatively rarely used. One last point: although they are usually not declared with a my declarator, subroutines themselves also have by default a lexical scope. If they are defined within a block, they will be seen only within that block. An example of this has been given at the end of the solution to the GCD exercise of the previous chapter (see Subsection A.3.7). That being said, you can declare a subroutine with a my declarator if you wish: my sub frobnicate { # ... } This technique might add some consistency or some form of self-documenting feature, but you wont buy very much added functionality with that. 6.6 Control Flow Statements (last, next, etc.) Sometimes you dont know its time to end a loop until you get half way through the body. In that case, you can use a control flow statement such as last to jump out of the loop. For example, suppose you want to take input from the user until they type done. You could write: while True { my $line = prompt "Enter something ('done' for exiting)\n"; last if $line eq "done"; say $line; } say 'Done!'; The loop condition is True, which is always true, so the loop runs until it hits the last statement. Each time through, it prompts the user to type something. If the user types done, the last statement exits the loop. Otherwise, the program echoes whatever the user types and goes back to the top of the loop. Heres a sample run: $ raku while_done.raku Enter something ('done' for exiting) Not done Not done Enter something ('done' for exiting) done Done! 92 Chapter 6. Iteration This way of writing while loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively (stop when this happens) rather than negatively (keep going until that happens). Using a while loop with a condition that is always true is a quite natural way of writing an infinite loop, i.e., a loop that will run forever until something else in the code (such as the last statement used above) forces the program to break out of the loop. This is commonly used in many programming languages, and this works well in Raku. There is, however, another common and more idiomatic way of constructing infinite loops in Raku: using the loop statement, which we will study in Section 9.7 (p. 150). For now, well use the while True statement, which is fairly legitimate. Sometimes, rather than simply breaking out of the while loop as with the last control statement, you need to start the body of the loop at the beginning. For example, you may want to check whether the user input is correct with some (unspecified) is-valid subroutine before processing the data, and ask the user to try again if the input was not correct. In this case, the next control statement lets you start at the top the loop body again: while True { my $line = prompt "Enter something ('done' for exiting)\n"; last if $line eq "done"; next unless is-valid($line); # further processing of $line; } print('Done!') Here, the loop terminates if the user types done. If not, the user input is checked by the is-valid subroutine; if the subroutine returns a true value, the processing continues forward; if it returns a false value, then the control flow starts again at the beginning of the body of the loop, so the user is prompted again to submit a valid input. The last and next control statements also work in for loops. For example, the following for loop iterates in theory on a range of integer numbers between 1 and 20, but discards odd numbers by virtue of a next statement and breaks out of the loop with a last statement as soon as the loop variable is greater than $max (i.e., 10 in this example): my $max = 10; for 1..20 -> $i { next unless $i %% 2; # keeps only even values last if $i > $max; # stops loop if $i is greater than $max say $i; # prints 2 4 6 8 10 } You may have as many last and next statements as you like, just as you may have as many return statements as you like in a subroutine. Using such control flow statements is not considered poor practice. During the early days of structured programming, some people insisted that loops and subroutines have only one entry and one exit. The one-entry notion is still a good idea, but the one-exit notion has led people to bend over backwards and write a lot of unnatural code. Much of programming consists of traversing decision trees. A decision tree naturally starts with a single trunk but ends with many leaves. Write your code with the number of loop controls (and subroutine exits) that is natural to the 6.7. Square Roots 93 problem youre trying to solve. If youve declared your variables with reasonable scopes, everything gets automatically cleaned up at the appropriate moment, no matter how you leave the block. 6.7 Square Roots Loops are often used in programs that compute numerical results by starting with an approximate answer and iteratively improving it. For example, one way of computing square roots is Newtons method (also known as the Newton-Raphsons method). Suppose that you want to know the square root of a. If you start with almost any estimate, x, you can compute a better estimate y with the following formula: y= x + a/x 2 For example, if a is 4 and x is 3: > my $a = 4; 4 > my $x = 3; 3 > my $y = ($x + $a/$x)/2; 2.166667 The result is closer than 3 to the correct answer ( 4 = 2) . If we repeat the process with the new estimate, it gets even closer: > $x = $y; 2.166667 > $y = ($x + $a/$x)/2; 2.006410 After a few more updates, the estimate is almost exact: > $x = $y; 2.006410 > $y = ($x + $a/$x)/2; 2.000010 > $x = $y; 2.000010 > $y = ($x + $a/$x)/2; 2.000000000026 In general we dont know ahead of time how many steps it takes to get to the right answer, but we know when we get there because the estimate stops changing: > $x = $y; 2.000000000026 94 Chapter 6. Iteration > $y = ($x + $a/$x)/2; 2 > $x = $y; 2 > $y = ($x + $a/$x)/2; 2 When $y == $x, we can stop. Here is a loop that starts with an initial estimate, x, and improves it until it stops changing: my ($a, $x) = (4, 3); while True { say "-- Intermediate value: $x"; my $y = ($x + $a/$x) / 2; last if $y == $x; $x = $y; } say "Final result is $x"; This will print: -- Intermediate -- Intermediate -- Intermediate -- Intermediate -- Intermediate -- Intermediate Final result is value: value: value: value: value: value: 2 3 2.166667 2.006410 2.000010 2.000000000026 2 For most values of $a this works fine, but there are a couple of caveats with this approach. First, in most programming languages, it is dangerous to test float equality, because floating-point values are only approximately right. We do not have this problem with Raku, because, as we have already mentioned, it is using a better representation of rational numbers than most generalist programming languages. (You may want to keep this in mind if you are using some other languages.) Even if we dont have this problem with Raku, there may also be some problems with algorithms that do not behave as well as Newtons algorithm. For example, some algorithms might not converge as fast and as neatly as Newtons algorithm but might instead produce alternate values above and below the accurate result. Rather than checking whether $x and $y are exactly equal, it is safer to use the built-in function abs to compute the absolute value, or magnitude, of the difference between them: last if abs($y - $x) < $epsilon: where epsilon has a very small value like 0.0000001 that determines how close is close enough. 6.8. Algorithms 6.8 95 Algorithms Newtons method is an example of an algorithm: it is a mechanical process for solving a category of problems (in this case, computing square roots). To understand what an algorithm is, it might help to start with something that is not an algorithm. When you learned to multiply single-digit numbers, you probably memorized the multiplication table. In effect, you memorized 100 specific solutions. That kind of knowledge is not algorithmic. But if you were lazy, you might have learned a few tricks. For example, to find the product of n and 9, you can write n 1 as the first digit and 10 n as the second digit. (For example, to figure out 9 7, n 1 is 6 and 10 n is 3, so that the product 9 7 is 63.) This trick is a general solution for multiplying any single-digit number by 9. Thats an algorithm! Similarly, the techniques you learned in school for addition (with carrying), subtraction (with borrowing), and long division are all algorithms. One of the characteristics of algorithms is that they do not require any intelligence to carry out. They are mechanical processes where each step follows from the last according to a simple set of rules. Executing algorithms is boring, but designing them is interesting, intellectually challenging, and a central part of computer science. Some of the things that people do naturally, without difficulty or conscious thought, are the hardest to express algorithmically. Understanding natural language is a good example. We all do it, but so far no one has been able to explain how we do it, at least not in the form of an algorithm. 6.9 Debugging As you start writing bigger programs, you might find yourself spending more time debugging. More code means more chances to make an error and more places for bugs to hide. One way to cut your debugging time is debugging by bisection. For example, if there are 100 lines in your program and you check them one at a time, it would take 100 steps. Instead, try to break the problem in half. Look at the middle of the program, or near it, for an intermediate value you can check. Add a say statement (or something else that has a verifiable effect) and run the program. If the midpoint check is incorrect, there must be a problem in the first half of the program. If it is correct, the problem is in the second half. Every time you perform a check like this, you halve the number of lines you have to search. After six steps (which is fewer than 100), you would be down to one or two lines of code, at least in theory. In practice it is not always clear what the middle of the program is and not always possible to check it. It doesnt make sense to count lines and find the exact midpoint. Instead, think about places in the program where there might be errors and places where it is easy to put a check. Then choose a spot where you think the chances are about the same that the bug is before or after the check. 96 Chapter 6. Iteration 6.10 Glossary Reassignment Assigning a new value to a variable that already exists. Update An assignment where the new value of the variable depends on the old. Initialization An assignment that gives an initial value to a variable that may later be updated. Increment An update that increases the value of a variable (often by one). Decrement An update that decreases the value of a variable. Iteration Repeated execution of a set of statements using either a recursive function call or a loop. Infinite loop A loop in which the terminating condition is never satisfied. Algorithm A general process for solving a category of problems. 6.11 Exercises Exercise 6.1. Copy the loop from Section 6.7 and encapsulate it in a subroutine called my-sqrt that takes $a as a parameter, chooses a reasonable value of $x, and returns an estimate of the square root of $a. To test it, write a function named test-square-root that prints a table like this: a 1 2 3 4 5 6 7 8 9 mysqrt(a) 1.0000000000000 1.4142135623747 1.7320508075689 2.0000000000000 2.2360679774998 2.4494897427832 2.6457513110647 2.8284271247494 3.0000000000000 sqrt(a) diff 1.0000000000000 1.110223e-15 1.4142135623731 1.594724e-12 1.7320508075689 0.000000e+00 2.0000000000000 0.000000e+00 2.2360679774998 0.000000e+00 2.4494897427832 8.881784e-16 2.6457513110646 1.025846e-13 2.8284271247462 3.189449e-12 3.0000000000000 0.000000e+00 The first column is a number, a, the second column is the square root of a computed with my-sqrt, the third column is the square root computed by the sqrt built-in function of Raku, and the fourth column is the absolute value of the difference between the two estimates. Dont worry too much about obtaining a clean tabular formatting, we havent seen the built-in functions to do that. Solution: A.4.1 Exercise 6.2. The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a numerical approximation of 1/: 2 2 (4k)!(1103 + 26390k ) 1 = 9801 k (k!)4 3964k =0 6.11. Exercises 97 Write a function called estimate-pi that uses this formula to compute and return an estimate of . It should use a while loop to compute terms of the summation until the last term is smaller than 1e-15 (which is Raku notation for 1015 ). You can check the result by comparing it to the built-in constant pi. Solution: A.4.2. 98 Chapter 6. Iteration Chapter 7 Strings Strings are not like integers, rationals, and Booleans. A string is a sequence of characters, which means it is an ordered collection of other values, and you sometimes need access to some of these individual values. In this chapter youll see how to analyze, handle, and modify strings, and youll learn about some of the methods strings provide. You will also start to learn about a very powerful tool for manipulating text data, regular expressions a.k.a. regexes. 7.1 A String is a Sequence A string is primarily a piece of textual data, but it is technically an ordered sequence of characters. Many programming languages allow you to access individual characters of a string with an index between brackets. This is not directly possible in Raku, but you still can access the characters one at a time using the comb built-in method and the bracket operator: > my $string = "banana"; banana > my $st = $string.comb; (b a n a n a) > say $st[1]; a > say $st[2]; n The comb in the second statement splits the string into a list of characters that you can then access individually with square brackets. The expression in brackets is called an index (it is sometimes also called a subscript). The index indicates which character in the sequence you want (hence the name). But this may not be what you expected: the item with index 1 is the second letter of the word. For computer scientists, the index is usually an offset from the beginning. The offset of the first letter (b) is zero, and the offset of the first a is 1, not 2, and so on. 100 Chapter 7. Strings You could also retrieve a slice of several characters in one go using the range operator within the brackets: > say $st[2..5] (n a n a) Again, the nana substring starts on the third letter of 'banana', but this letter is indexed 2, and the sixth letter is index 5. But, even if all this might be useful at times, this is not the way you would usually handle strings in Raku, which has higher level tools that are more powerful and more expressive, so that you seldom need to use indexes or subscripts to access individual characters. Also, if there is a real need to access and manipulate individual letters, it would make more sense to store them in an array, but we havent covered arrays yet, so well have to come back to that later. 7.2 Common String Operators Raku provides a number of operators and functions to handle strings. Lets review some of the most popular ones. 7.2.1 String Length The first thing we might want to know about a string is its length. The chars built-in returns the number of characters in a string and can be used with either a method or a function syntax: > say "banana".chars; 6 > say chars "banana"; 6 # method invocation syntax # function call syntax Note that, with the advent of Unicode, the notion of string length has become more complicated than it used to be in the era of ASCII-only strings. Today, a character may be made of one, two, or more bytes. The chars routine returns the number of characters (in the sense of Unicode graphemes, which is more or less what humans perceive as characters) within the string, even if some of these characters require an encoding over 2, 3, or 4 bytes. A string with a zero length (i.e., no character) is called an empty string. 7.2.2 Searching For a Substring Within the String The index built-in usually takes two arguments, a string and a substring (sometimes called the haystack and the needle), searches for the substring in the string, and returns the position where the substring is found (or an undefined value if it wasnt found): > say index "banana", "na"; 2 > say index "banana", "ni"; Nil 7.2. Common String Operators 101 Here again, the index is an offset from the beginning of the string, so that the index of the first letter (b) is zero, and the offset of the first n is 2, not 3. You may also call index with a method syntax: > say "banana".index("na"); 2 The index function can take a third optional argument, an integer indicating where to start the search (thus ignoring in the search any characters before the start position): > say index "banana", "na", 3; 4 Here, the index function started the search on the middle a and thus found the position of the second occurrence of the na substring. There is also a rindex function, which searches the string backwards from the end and returns the last position of the substring within the string: > say rindex "banana", "na"; 4 Note that even though the rindex function searches the string backwards (from the end), it returns a position computed from the start of the string. 7.2.3 Extracting a Substring from a String The opposite of the index function is the substr function or method, which, given a start position and a length, extracts a substring from a string: > say substr "I have a dream", 0, 6; I have > say "I have a dream".substr(9, 5) dream Note that, just as for the chars function, the length is expressed in characters (or Unicode graphemes), not in bytes. Also, as you can see, spaces separating words within the string obviously count as characters. The length argument is optional; if it is not provided, the substr function returns the substring starting on the start position to the end of the string: > say "I have a dream".substr(7) a dream Similarly, if the length value is too large for the substring starting on the start position, the substr function will also return the substring starting on the start position to the end of the string: > say substr "banana", 2, 10; nana 102 Chapter 7. Strings Of course, the start position and length parameters need not be hardcoded numbers as in the examples above; you may use a variable instead (or even an expression or a function returning a numeric value), provided the variable or value can be coerced into an integer. But the start position must be within the string range, failing which you would obtain a Start argument to substr out of range ... error; so you may have to verify it against the length of the string beforehand. You can also start counting backwards from the end of the string with the following syntax: > say "I have a dream".substr(*-5) dream > say substr "I have a dream", *-5; dream Here, the star * may be thought as representing the total size of the string; *-5 is therefore the position in the string five characters before the end of the string. So, substr(*-5) returns the characters from that position to the end of the string, i.e., the last five characters of the string. 7.2.4 A Few Other Useful String Functions or Methods This may not be obvious yet, but we will see soon that the combination of the above string functions gives you already a lot of power to manipulate strings way beyond what you may think possible at this point. Let us just mention very briefly a few additional functions that may prove useful at times. 7.2.4.1 flip The flip function or method reverses a string: > say flip "banana"; ananab 7.2.4.2 split The split function or method splits a string into substrings, based on delimiters found in the string: > say $_ for split "-", "25-12-2016"; 25 12 2016 > for "25-12-2016".split("-") -> $val {say $val}; 25 12 2016 The delimiter can be a single quoted character as in the examples above or a string of several characters, such as a comma and a space in the example below: 7.2. Common String Operators > .say for split Jan Feb Mar 103 ", ", "Jan, Feb, Mar"; Remember that .say is a shortcut for $_.say. By default, the delimiters dont appear in the output produced by the split function or method, but this behavior can be changed with the use of an appropriate adverb. An adverb is basically a named argument to a function that modifies the way the function behaves. For example, the :v (values) adverb tells split to also output the value of the delimiters: > .perl.say for split "Jan" ", " "Feb" ", " "Mar" ', ', "Jan, Feb, Mar", :v; The other adverbs that can be used in this context are :k (keys), :kv (keys and values), and :p (pairs). Their detailed meaning can be found in the documentation for split (https: //docs.raku.org/routine/split). The skip-empty adverb removes empty chunks from the result list. The split function can also use a regular expression pattern as delimiter, and this can make it much more powerful. We will study regular expressions later in this chapter. 7.2.4.3 String Concatenation The ~ operator concatenates two strings into one: > say "ban" ~ "ana"; banana You may chain several occurrences of this operator to concatenate more than two strings: > say "ba" ~ "na" ~ "na"; banana Used as a unary prefix operator, ~ stringifies (i.e., transforms into a string) its argument: > say (~42).WHAT; (Str) 7.2.4.4 Splitting on Words The words function returns a list of words that make up the string: > say "I have a dream".words.perl; ("I", "have", "a", "dream").Seq > .say for "I have a dream".words; I have a dream 104 Chapter 7. Strings 7.2.4.5 join The join function takes a separator argument and a list of strings as arguments; it interleaves them with the separator, concatenates everything into a single string, and returns the resulting string. This example illustrates the chained use of the words and join functions or methods: say 'I have a dream'.words.join('|'); say join ";", words "I have a dream"; # -> I|have|a|dream # -> I;have;a;dream In both cases, words first splits the original string into a list of words, and join stitches the items of this list back into a new string interleaved with the separator. 7.2.4.6 Changing the Case The lc and uc routines return respectively a lowercase and an uppercase version of their arguments. There is also a tc function or method returning its argument with the first letter converted to title case (or upper case): say say say say lc "April"; "April".lc; uc "april"; tc "april"; # # # # -> -> -> -> april april APRIL April Remember also that the eq operator checks the equality of two strings. String Traversal With a while or for Loop 7.3 A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it or with it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a while loop and the index function: my $index = 0; my $fruit = "banana"; while $index < $fruit.chars { my $letter = substr $fruit, $index, 1; say $letter; $index++; } This will output each letter, one at a time: b a n a n a 7.3. String Traversal With a while or for Loop 105 This loop traverses the string and displays each letter on a line by itself. The loop condition is $index < $fruit.chars, so when $index is equal to the length of the string, the condition is false, and the body of the loop doesnt run. In other words, the loop stops when $index is the length of the string minus one, which corresponds to the last character of the string. As an exercise, write a function that takes a string as an argument and displays the letters backward, one per line. Do it at least once without using the flip function. Solution: A.5.1 Another way to write a traversal is with a for loop: my $fruit = "banana"; for $fruit.comb -> $letter { say $letter } Each time through the loop, the next character in the string is assigned to the variable $letter. The loop continues until no characters are left. The loop could also use the substr function: for 0..$fruit.chars - 1 -> $index { say substr $fruit, $index, 1; } The following example shows how to use concatenation and a for loop to generate an abecedarian series (that is, in alphabetical order). In Robert McCloskeys book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order: my $suffix = 'ack'; for 'J'..'Q' -> $letter { say $letter ~ $suffix; } The output is: Jack Kack Lack Mack Nack Oack Pack Qack Of course, thats not quite right because Ouack and Quack are misspelled. As an exercise, modify the program to fix this error. Solution: A.5.2. 106 7.4 Chapter 7. Strings Looping and Counting The following program counts the number of times the letter a appears in a string: my $word = 'banana'; my $count = 0; for $word.comb -> $letter { $count++ if $letter eq 'a'; } say $count; # -> 3 This program demonstrates another pattern of computation called a counter. The variable $count is initialized to 0 and then incremented each time an a is found. When the loop exits, $count contains the resultthe total number of occurrences of letter a. As an exercise, encapsulate this code in a subroutine named count, and generalize it so that it accepts the string and the searched letter as arguments. Solution: A.5.3. 7.5 Regular Expressions (Regexes) The string functions and methods we have seen so far are quite powerful, and can be used for a number of string manipulation operations. But suppose you want to extract from the string yellow submarine any letter that is immediately preceded by the letter l and followed by the letter w. This kind of fuzzy search can be done in a loop, but this is somewhat unpractical. You may try to do it as an exercise if you wish, but you should be warned: it is quite tricky and difficult. Even if you dont do it, the solution may be of some interest to you: see SubsectionA.5.4. If you add some further condition, for example that this letter should be extracted or captured (i.e. saved for later use) only if the rest of the string contains the substring rin, this starts to be really tedious. Also, any change to the requirements leads to a substantial rewrite or even complete refactoring of the code. For this type of work, regular expressions or regexes are a much more powerful and expressive tool. Heres one way to extract letters using the criteria described above: > my $string = "yellow submarine"; yellow submarine > say ~$0 if $string ~~ / l (.) w .*? rin /; o Dont worry if you dont understand this example; hopefully it will be clear very soon. The ~~ operator is called the smart match operator. It is a very powerful relational operator that can be used for many advanced comparison tasks. In this case, it checks whether the $string variable on its left matches the funny expression on its right, i.e., as a first approximation, whether the expression on the right describes the string (or part of it). The / l (.) w .*? rin / part is called a regex pattern and means: the letter l, followed by any single character (the dot) to be captured (thanks to the parentheses), followed by the letter w, followed by an unspecified number of characters, followed by the substring rin. Phew! All this in one single code line! Quite powerful, isnt it? If the string matches 7.6. Using Regexes 107 the pattern, then the match will return a true value and $0 will be populated with the character to be capturedthe letter o in this case. Unless specified otherwise (we will see how later), white space is not significant within a regex pattern. So you can add spaces within a pattern to separate its pieces and make your intentions clearer. Most of the rest of this chapter will cover the basics of constructing such regex patterns and using them. But the concept of regexes is so crucial in Raku that we will also devote a full chapter to this subject and some related matters (Chapter 13). The notion of regular expressions is originally a concept stemming from the theory of formal languages. The first uses of regular expressions in computing came from Unix utilities, some of which still remain in wide use today, such as grep, created by Ken Thomson in 1973, sed (ca. 1974), and awk, developed a few years later (in 1977) by Aho, Weinberger, and Kernighan. Early versions of Perl, the language from which Raku is derived, included an extended version of regular expressions, that has since been imitated by many other recent languages. The difference, though, is that regular expressions are deeply rooted within the core of the Perl and Raku languages, whereas most other languages have adopted them as an add-on or a plug-in, often based or derived on a library known as Perl Compatible Regular Expressions (PCRE). The Raku regular expressions have extended these notions so much that they have little to do with the original language theory concept, so that it has been deemed appropriate to stop calling them regular expressions and to speak about regexes, i.e., a sort of patternmatching sublanguage that works similarly to regular expressions. 7.6 Using Regexes A simple way to use a regex is to use the smart match operator ~~: say "Matched" if "abcdef" ~~ / bc.e /; # -> Matched Here, the smart match operator compares the abcdef string with the /bc.e/ pattern and reports a success, since, in this case, the bc in the string matches the bc part of the pattern, the dot in the pattern matches any character in the string (and matches in this case d) and, finally, the e of the string matches the e in the pattern. The part of the string that was matched is contained in the $/ variable representing the match object, which we can stringify with the ~ operator. We can make good use of this to better visualize the part of the string that was matched by the regex pattern: say ~$/ if "abcdef" ~~ / bc.e /; # -> bcde The matching process might be described as follows (but please note that this is a rough simplification): look in the string (from left to right) for a character matching the first atom (i.e., the first matchable item) of the pattern; when found, see whether the second character can match the second atom of the pattern, and so on. If the entire pattern is used, then the regex is successful. If it fails during the process, start again from the position immediately after the initial match point. (This is called backtracking). And repeat that until one of following occurs: 108 Chapter 7. Strings There is a successful match, in which case the process ends and success is reported. The string has been exhausted without finding a match, in which case the regex failed. Let us examine an example of backtracking: say "Matched" if "abcabcdef" ~~ / bc.e /; # -> Matched Here, the regex engine starts by matching bca with bc., but that initial match attempt fails, because the next letter in the string, b, does not match the e of the pattern. The regex engine backtracks and starts the search again from the third letter (c) of the string. It starts a new match on the fifth letter of the string (the second b), manages to match successfully bcde, and exits with a successful status (without even looking for any further match). If the string to be analyzed is contained in the $_ topical variable, then the smart match operator is implicit and the syntax is even simpler: for 'abcdef' { say "Matched" if / cd.f /; } # $_ now contains 'abcdef' # -> Matched You might also use a method invocation syntax: say "Matched" if "abcdef".match(/ b.d.f /); # -> Matched In all cases we have seen so far, we directly used a pattern within a pair of / slash delimiters. We can use other delimiters if we prefix our pattern with the letter m: say "Matched" if "abcdef" ~~ m{ bc.e }; # -> Matched say "Matched" if "abcdef" ~~ m! bc.e !; # -> Matched or: The m operator does not alter the way a regex works; it only makes it possible to use delimiters other than slashes. Said differently, the m prefix is the standard way to introduce a pattern, but it is implicit and can be omitted when the pattern is delimited with slashes. It is probably best to use slashes, because thats what people commonly use and recognize immediately, and to use other delimiters only when the regex pattern itself contains slashes. A pattern may also be stored in a variable (or, more accurately, in a regex object), using the rx// operator: my $regex = rx/c..f/; say "Matched" if 'abcdef' ~~ $regex; # -> Matched 7.7. Building your Regex Patterns 7.7 109 Building your Regex Patterns It is now time to study the basic building blocks of a regex pattern. 7.7.1 Literal Matching As you have probably figured out by now, the simplest case of a regex pattern is a constant string. Matching a string against such a regex is more or less equivalent to searching for that string with the index function: my $string = "superlative"; say "$string contains 'perl'." if $string ~~ /perl/; # -> superlative contains 'perl'. Note however that, for such literal matches, the index function discussed earlier is likely to be slightly more efficient than a regex on large strings. The contains method, which returns true if its argument is a substring of its invocant, is also likely to be faster. Alphanumeric characters and the underscore _ are literal matches. All other characters must either be escaped with a backslash (for example \? to match a question mark), or included in quotes: say say say say 7.7.2 "Success" "Success" "Success" "Success" if if if if 'name@company.uk' 'name@company.uk' 'name@company.uk' 'name@company.uk' ~~ ~~ ~~ ~~ / / / / name@co /; # Fails to compile 'name@co' /; # -> Success name\@co/ ; # -> Success name '@' co /; # -> Success Wildcards and Character Classes Regexes wouldnt be very useful if they could only do literal matching. We are now getting to the more interesting parts. In a regex pattern, some symbols can match not a specific character, but a whole family of characters, such as letters, digits, etc. They are called character classes. We have already seen that the dot is a sort of wildcard matching any single character of the target string: my $string = "superlative"; say "$string contains 'pe.l'." if $string ~~ / pe . l /; # -> superlative contains 'pe.l'. The example above illustrates another feature of regexes: whitespace is usually not significant within regex patterns (unless specified otherwise with the : s or : sigspace adverb, as we will see later). There are predefined character classes of the form \w. Its negation is written with an uppercase letter, \W. The \w (word character) character class matches one single alphanumeric character (i.e., among alphabetical characters, digits, and the _ character). \W will match any other character. Note however that Raku is Unicode-compliant and that, for example, letters of the Greek or Cyrillic alphabets or Thai digits will be matched by \w: 110 Chapter 7. Strings say "Matched" if 'abc' ~~ / ab\w\w /; # -> Matched Here, the string was matched because, according to the Unicode standard, (G REEK SMALL LETTER DELTA ) is a letter and it therefore belongs to the \w character class. Other common character classes include: \d (digits) and \D (non-digits) \s (whitespace) and \S (non-whitespace) \n (newline) and \N (non-newline). say ~$/ if 'Bond 007' ~~ /\w\D\s\d\d\d/; # -> "nd 007" Here, weve matched nd 007, because we have found one word character (n), followed by a non digit (d), followed by a space, followed by three digits. You can also specify your own character classes by inserting between <[ ]> any number of single characters and ranges of characters (expressed with two dots between the end points), with or without whitespace. For example, a character class for a hexadecimal digit might be: <[0..9 a..f A..F]> You can negate such a character class by inserting a - after the opening angle bracket. For example, a string is not a valid hexadecimal integer if it contains any character not in <[0..9a..fA..F]>, i.e., any character matched by the negated hexadecimal character class: say "Not an hex number" if $string ~~ /<-[0..9 a..f A..F]>/; Please note that you generally dont need to escape nonalphanumerical characters in your character classes: say ~$/ if "-17.5" ~~ /(<[\d.-]>+)/; # -> -17.5 In this example, we use the + quantifier that well discuss in the next section, but the point here is that you dont need to escape the dot and the dash within the character class definition. 7.7.3 Quantifiers A quantifier makes a preceding atom1 match not exactly once, but rather a specified or variable number of times. For example a+ matches one or more a characters. In the following code, the \d+ matches one or more digits (three digits in this case): say ~$/ if 'Bond 007' ~~ /\w\D\s\d+/; # -> "nd 007" 1 The word atom means a single character or several characters or other atoms grouped together (by a set of parentheses or square brackets). 7.7. Building your Regex Patterns 111 The predefined quantifiers include: +: one or more times; : zero or more times; ?: zero or one match. The + and quantifiers are said to be greedy, which means that they match as many characters as they can. For example: say ~$/ if 'aabaababa' ~~ / .+ b /; # -> aabaabab Here, the .+ matches as much as it possibly can of the string, while still being able to match the final b. This is often what you want, but not always. Perhaps your intention was to match all letters until the first b. In such cases, you would use the frugal (nongreedy) versions of those quantifiers, which are obtained by suffixing them with a question mark: +? and ?. A frugal quantifier will match as much as it has to for the overall regex to succeed, but not more than that. To match all letters until the first b, you could use: say ~$/ if 'aabaababa' ~~ / .+? b /; # -> aab You can also specify a range (min..max) for the number of times an atom may be matched. For example, to match an integer smaller than 1,000: say 'Is a number < 1,000' if $string ~~ / ^ \d ** 1..3 $ /; This matches one to three digits. The ^ and $ characters are anchors representing the beginning and the end of the string and will be covered in the next section. For matching an exact number of times, just replace the range with a single number: say 'Is a 3-digit number' if $num ~~ / ^ \d ** 3 $ /; 7.7.4 Anchors and Assertions Sometimes, matching a substring is not good enough; you want to match the whole string, or you want the match to occur at the beginning or at the end of the string, or at some other specific place within the string. Anchors and assertions make it possible to specify where the match should occur. They need to match successfully in order for the whole regex to succeed, but they do not use up characters while matching. 7.7.4.1 Anchors The most commonly used anchors are the ^ start of string and $ end of string anchors: my $string = say "$string say "$string say "$string "superlative"; starts with 'perl'" if $string ~~ /^perl/; # (No output) ends with 'perl'" if $string ~~ /perl$/; # (No output) equals 'perl'" if $string ~~ /^perl$/; # (No output) 112 Chapter 7. Strings All three regexes above fail because, even though $string contains the perl substring, the substring is neither at the start, nor at the end of the string. In the event that you are handling multiline strings, you might also use the ^^ start of line and $$ end of line anchors. There are some other useful anchors, such as the << start of word (or word left boundary) and >> end of word (or word right boundary) anchors. 7.7.4.2 Look-Around Assertions Look-around assertions make it possible to specify more complex rules: for example, match foo, but only if preceded (or followed) by bar (or not preceded or not followed by bar): say "foobar" ~~ /foo /; # -> foo (lookahead assertion) say "foobaz" ~~ /foo /; # -> Nil (regex failed) say "foobar" ~~ / bar/; # -> bar (lookbehind assertion) Using an exclamation mark instead of a question mark transforms these look-around assertion into negative assertions. For example: say "foobar" ~~ /foo /; # -> foo say "foobaz" ~~ /foo /; # -> Nil (regex failed) say "foobar" ~~ / bar/; # -> Nil (regex failed) I assume that the examples above are rather clear. Look into the documentation (https: //docs.raku.org/language/regexes#Look-around_assertions) if you need further details. 7.7.4.3 Code Assertions You can also include a code assertion {...}>, which will match if the code block returns a true value: > say ~$/ if /\d\d {$/ == 42}>/ for ; 42 A negative code assertion will match unless the code block returns a true value: > say ~$/ if /\d\d / for 12 34 50 Code assertions are useful to specify conditions that cannot easily be expressed as regexes. They can also be used to display something, for example for the purpose of debugging a regex by printing out information about partial matches: 7.7. Building your Regex Patterns 113 > say "Matched $/" if "A12B34D50" ~~ /(\D) { say ~$0}> \d\d$/; A B D Matched D50 The output shows the various attempted matches that failed (A and B) before the backtracking process ultimately led to success (D50 at the end of the string). However, code assertions are in fact rarely needed for such simple cases, because you can very often just add a simple code block for the same purpose: > say "Matched $/" if "A12B34D50" ~~ /(\D) { say ~$0} \d\d$/; This code produces the same output, and there is no need to worry about whether the block returns a true value. 7.7.5 Alternation Alternations are used to match one of several alternatives. For example, to check whether a string represents one of the three base image colors (in JPEG and some other image formats), you might use: say 'Is a JPEG color' if $string ~~ /^ [ red | green | blue ] $/; There are two forms of alternations. First-match alternation uses the || operator and stops on the first alternative that matches the pattern: say ~$/ if "abcdef" ~~ /ab || abcde/; # -> ab Here, the pattern matches ab, without trying to match any further, although there would be an arguably better (i.e., longer) match with the other alternative. When using this type of alternation, you have to think carefully about the order in which you put the various alternatives, depending on what you need to do. The longest-match alternation uses the | operator and will try all the alternatives and match the longest one: say ~$/ if "abcdef" ~~ /ab | abcde/; # -> abcde Beware, though, that this will work as explained only if the alternative matches all start on the same position within the string: say ~$/ if "abcdef" ~~ /ab | bcde/; # -> ab Here, the match on the leftmost position wins (this is a general rule with regexes). 114 Chapter 7. Strings 7.7.6 Grouping and Capturing Parentheses and square brackets can be used to group things together or to override precedence: / / / / / / / a || bc / # matches 'a' or 'bc' ( a || b ) c / # matches 'ac' or 'bc' [ a || b ] c / # Same: matches 'ac' or 'bc', non-capturing grouping a b+ / # Matches an 'a' followed by one or more 'b's (a b)+ / # Matches one or more sequences of 'ab' [a b]+ / # Matches one or more sequences of 'ab', non-capturing (a || b)+ / # Matches a sequence of 'a's and 'b's(at least one) The difference between parentheses and square brackets is that parentheses dont just group things together, they also capture data: they make the string matched within the parentheses available as a special variable (and also as an element of the resulting match object): my $str = 'number 42'; say "The number is $0" if $str ~~ /number\s+ (\d+) /; # -> The number is 42 Here, the pattern matched the $str string and the part of the pattern within parentheses was captured into the $0 special variable. Where there are several parenthesized groups, they are captured into variables named $0, $1, $2, etc. (from left to right counting the open parentheses): say "$0 $1 $2" if "abcde" ~~ /(a) b (c) d (e)/; # -> a c e # or: say "$/[0..2]" if "abcde" ~~ /(a) b (c) d (e)/; # -> a c e The $0, $1, etc. variables are actually a shorthand for $/[0], $/[1], the first and second items of the matched object in list context, so that printing "The number is $/[0]" would have had the same effect. As noted, the parentheses perform two roles in regexes: they group regex elements and they capture what is matched by the subregex within parentheses. If you want only the grouping behavior, use square brackets [ ... ] instead: say ~$0 if 'cacbcd' ~~ / [a||b] (c.) /; # -> cb Using square brackets when there is no need to capture text has the advantage of not cluttering the $0, $1, $2, etc. variables, and it is likely to be slightly faster. 7.7.7 Adverbs (a.k.a. Modifiers) Adverbs modify the way the regex engine works. They often have a long form and a shorthand form. For example, the :ignorecase (or :i) adverb tells the compiler to ignore the distinction between upper case and lower case: 7.7. Building your Regex Patterns 115 > say so 'AB' ~~ /ab/; False > say so 'AB' ~~ /:i ab/; True The so built-in used here coerces its argument (i.e., the value returned by the regex match expression) into a Boolean value. If placed before the pattern, an adverb applies to the whole pattern: > say so 'AB' ~~ m:i/ ab/; True The adverb may also be placed later in the pattern and affects in this case only the part of the regex that comes afterwards: > say so 'AB' ~~ /a :i b/; False > say so 'aB' ~~ /a :i b/; True I said earlier that whitespace is usually not significant in regex patterns. The :sigspace or :s adverb makes whitespace significant in a regex: > say so 'ab' ~~ /a+ b/; True > say so 'ab' ~~ /:s a+ b/; False > say so 'ab' ~~ /:s a+b/; True Instead of searching for just one match and returning a match object, the :global or :g adverb tells the compiler to search for every non-overlapping match and return them in a list: > say "Word count = ", $/.elems if "I have a dream" ~~ m:g/ \w+/; Word count = 4 > say ~$/[3]; dream These are the most commonly used adverbs. Another adverb, :ratchet or :r, tells the regex engine not to backtrack and is very important for some specific uses, but we will come back to it in a later chapter (see section 13.4). 7.7.8 Exercises on Regexes As a simple exercise, write some regexes to match and capture: A succession of 10 digits within a longer string; A valid octal number (octal numbers use only digits 0 to 7); 116 Chapter 7. Strings The first word at the start of a string (for the purpose of these small exercises, the word separator may be deemed to be a space, but you might do it without this assumption); The first word of a string starting with an a; The first word of a string starting with a lower case vowel; A French mobile telephone number (in France, mobile phone numbers have 10 digits and start with 06 or 07); assume the digits are consecutive (no spaces); The first word of a string starting with a vowel in either upper- or lowercase; The first occurrence of a double letter (the same letter twice in a row); The second occurrence of a double letter; Solution: A.5.5 7.8 Putting It All Together This section is intended to give a few examples using several of the regex features we have seen for solving practical problems together. 7.8.1 Extracting Dates Assume we have a string containing somewhere a date in the YYYY-MM-DD format: my $string = "Christmas : 2016-12-25."; As mentioned earlier, one of the mottos in Raku is There is more than one way to do it (TIMTOWTDI). The various examples below should illustrate that principle quite well by showing several different ways to retrieve the date in the string: Using a character class (digits and dash): say ~$0 if $string ~~ /(<[\d-]>+)/; # -> 2016-12-25 Using a character class and a quantifier to avoid matching some small numbers elsewhere in the string if any: say ~$0 if $string ~~ /(<[\d-]> ** 10)/; # -> 2016-12-25 Using a more detailed description of the date format: say ~$/ if $string ~~ /(\d ** 4 \- \d\d \- \d\d)/; The same regex, but using an additional grouping to avoid repetition of the \- \d\d sub-pattern: say ~$/[0] if $string ~~ /(\d ** 4 [\- \d\d] ** 2 )/; Capturing the individual elements of the date: $string ~~ /(\d ** 4) \- (\d\d) \- (\d\d)/; my ($year, $month, $day) = ~$0, ~$1, ~$2; 7.8. Putting It All Together 117 Note that using the tilde as a prefix above leads $year, $month, and $day to be populated with strings. Assuming you want these variables to contain integers instead, you might nummify them, i.e., coerce them to numeric values using the prefix + operator: $string ~~ /(\d ** 4) \- (\d\d) \- (\d\d)/; my ($year, $month, $day) = +$0, +$1, +$2; Using subpatterns as building blocks: my $y = rx/\d ** 4/; my $m = rx/\d ** 2/; my $d = rx/\d ** 2/; $string ~~ /(<$y>) \- (<$m>) \- (<$d>)/; my ($year, $month, $day) = ~$0, ~$1, ~$2; Using subpatterns as building blocks is a quite efficient way of constructing step-bystep complicated regexes, but will see in Chapter 13 even better ways of doing this type of things. We could improve the $m (month) sub-pattern so that it matches only 01 to 12 and thus verify that it matches a valid month number: my $m = rx { 1 <[0..2]> # 10 to 12 || 0 <[1..9]> # 01 to 09 }; As you can see, using comments and whitespace helps make the regexs intent clearer. Another way of achieving the same goal is to use a code assertion to check that the value is numerically between 1 and 12: my $m = rx /\d ** 2 { 1 <= $/ <= 12 }> /; As an exercise, you could try to validate that the $d (day) subpattern falls within the 01 to 31 range. Try to use both validation techniques outlined just above. The $/ match object has the prematch and postmatch methods for extracting what comes before and after the matched part of the string: $string ~~ /(\d ** 4) \- (\d\d) \- (\d\d)/; say $/.prematch; # -> "Christmas : " say $/.postmatch; # -> "." As an exercise, try to adapt the above regexes for various other date formats (such as DD/MM/YYYY or YYYY MM, DD) and test them. If youre trying with the YYYY MM, DD format, please remember that spaces are usually not significant in a regex pattern, so you may need either to specify explicit spaces (using for example the \s character class) or to employ the :s adverb to make whitespace significant). 7.8.2 Extracting an IP Address Assume we have a string containing an IP-v4 address somewhere. IP addresses are most often written in the dot-decimal notation, which consists of four octets of the address expressed individually in decimal numbers and separated by periods, for example 17.125.246.28. For the purpose of these examples, our sample target string will be as follows: 118 Chapter 7. Strings my $string = "IP address: 17.125.246.28;"; Lets now try a few different ways to capture the IP address in that string, in the same way as we just did for the dates: Using a character class: say ~$0 if $string ~~ /(<[\d.]>+)/; # -> 17.125.246.28 Using a character class and a quantifier (note that each octet may have one to three digits, so the total number of characters may vary from 7 to 15): say ~$0 if $string ~~ /(<[\d.]> ** 7..15)/; Using a more detailed description of the IP format: say ~$/ if $string ~~ /([\d ** 1..3 \.] ** 3 \d ** 1..3 )/; Using subpatterns as building blocks: my $octet = rx/\d ** 1..3/; say ~$/ if $string ~~ /([<$octet> \.] ** 3 <$octet>)/; The maximal value of an octet is 255. We can refine somewhat the definition of the $octet subpattern: my $octet = rx/<[1..2]>? \d ** 1..2/; say ~$/ if $string ~~ /([<$octet> \.] ** 3 <$octet>)/; With this definition of the $octet pattern, the regex would match any number of one or two digits, or a three-digit number starting with digits 1 to 2. But that is not good enough if we really want to check that the IP address is valid (for example, it would erroneously accept 276 as a valid octet). The definition of the $octet subpattern can be further refined to really match only authorized values: my $octet = rx { ( 25 || 2 || 1 || \d <[0..5]> <[0..4]> \d \d ** 2 ** 1..2 # # # # 250 to 255 200 to 249 100 to 199 0 to 99 ) }; say ~$/ if $string ~~ /([<$octet> \.] ** 3 <$octet>)/; This definition of $octet illustrates once more how the abundant use of whitespace and comments can help make the intent clearer. We could also use a code assertion to limit the value of an $octet to the 0..255 range: my $octet = = rx{(\d ** 1..3) {0 <= $0 <= 255 }> }; say ~$/ if $string ~~ /([<$octet> \.] ** 3 <$octet>)/; 7.9 Substitutions Replacing part of a string with some other substring is a very frequent requirement in string handling. This might be needed for spelling corrections, data reformatting, removal of personal information from data, etc. 7.9. Substitutions 7.9.1 119 The subst Method Raku has a subst method which can replace some text with some other text: my $string = "abcdefg"; $string = $string.subst("cd", "DC"); # -> abDCefg The first argument to this method is the search part, and can be a literal string, as in the example above, or a regex: my $string = "abcdefg"; $string = $string.subst(/c \w+ f/, "SUBST"); 7.9.2 # -> abSUBSTg The s/search/replace/ Construct The most common way to perform text substitution in Raku is the s/search/replace/ construct, which is quite concise, plays well within the general regex syntax, and has the advantage of enabling in-place substitution. This is an example of the standard syntax for this type of substitution: my $string = "abcdefg"; $string ~~ s/ c \w+ f /SUBST/; # -> abSUBSTg Here, the search part is a regex and the replacement part is a simple string (no quotation marks needed). If the input string is contained in the $_ topical variable, you dont need to use the smart match operator: $_ = "abcdefg"; s/c \w+ f/SUBST/; # -> abSUBSTg The delimiters dont need to be slashes (and this can be quite useful if either the search or the replacement contain slashes): my $str = " foo foo"; $str ~~ s!'foo'!bar!; # ->foo bar Unless specified otherwise (with an adverb), the substitution is done only once, which helps to prevent unexpected results: $_ = 'There can be twly two'; s/tw/on/; # Replace 'tw' with 'on' once .say; # There can be only two If the substitution were done throughout the string, two would have been replaced by ono, clearly not the expected result. 120 Chapter 7. Strings 7.9.3 Using Captures If the regex on the lefthand side contains captures, the replacement part on the righthand side can use the $O, $1, $2, etc. variables on the right side to insert captured substrings in the replacement text. A typical example of that is date reformatting: my $string = "Xmas = 2016-12-25"; $string ~~ s/(\d ** 4) \- (\d\d) \- (\d\d)/$2-$1-$0/; # $string is now: Xmas = 25-12-2016 7.9.4 Adverbs The adverbs discussed above (Section 7.7.7) can be used with the substitution operator. The modifiers most commonly used in substitutions are the :ignorecase (or :i) and :global (or :g) adverbs. They work just as described in Subsection 7.7.7 of the section on regexes and matching. The one specific point to be made here is that substitutions are usually done only once. But with the :global (or :g) adverb, they will be done throughout the whole string: my $string = "foo bar bar foo bar"; $string ~~ s:g/bar/baz/; # string is now "foo baz baz foo baz" 7.10 Debugging When you use indices to traverse the values in a sequence, it is tricky to get the beginning and end of the traversal right. Here is a subroutine that is supposed to compare two words and return True if one of the words is the reverse of the other, but it contains two errors: # ATTENTION, watch out: code with errors sub is-reverse(Str $word1, Str $word2) { return False if $word1.chars != $word2.chars; my $i = 0; my $j = $word2.chars; while $j > 0 { return False if substr($word1, $i, 1) ne substr($word2, $j, 1); $i++; $j--; } return True; } say is-reverse "pots", "stop"; The first postfix if statement checks whether the words are the same length. If not, we can return False immediately. Otherwise, for the rest of the subroutine, we can assume that the words are the same length. This is an example of the guardian pattern described in Section 5.9 (p. 79). 7.10. Debugging 121 $i and $j are indices: $i traverses $word1 forward while $j traverses $word2 backward. If we find two letters that dont match, we can return False immediately. If we get through the whole loop and all the letters match, we return True. If we test this function with the words stop and pots, we expect the return value True, but we get False instead. So, whats wrong here? With this kind of code, the usual suspect is a possible blunder in the management of indices (especially perhaps an off-by-one error). For debugging this kind of error, the first move might be to print the values of the indices immediately before the line where they are used: sub is-reverse(Str $word1, Str $word2) { return False if $word1.chars != $word2.chars; my $i = 0; my $j = $word2.chars; } while $j > 0 { say '$i = ', $i, ' $j = ', $j; return False if substr($word1, $i, 1) ne substr($word2, $j, 1); $i++; $j--; } return True; Now when we run the program again, we get more information: $i = 0 $j = 4 False The first time through the loop, the value of $j is 4, which is out of range for the string 'pots'. The index of the last character is 3, so the initial value for $j should be $word2.chars - 1. Note that in the event that this was still not enough for us to spot the out-of-range error, we could have gone one step further and printed the letters themselves, and we would have seen that we did not get the last letter of the second word. If we fix that error and run the program again, we get: $i = 0 $j = 3 $i = 1 $j = 2 $i = 2 $j = 1 True This time we get the right answer, but it looks like the loop only ran three times, which is suspicious: it seems that the program did not compare the last letter of the first word (indexed $i = 3) with the last letter of the second word (indexed $j = 0). We can confirm this by running the subroutine with the following arguments: stop and lots, which displays: 122 Chapter 7. Strings Figure 7.1: State diagram. $i = 0 $j = 3 $i = 1 $j = 2 $i = 2 $j = 1 True This is obviously wrong, lots is not the reverse of stop, the subroutine should return False. So we have another bug here. To get a better idea of what is happening, it is useful to draw a state diagram. During the first iteration, the frame for is_reverse is shown in Figure 7.1. We took some license by arranging the variables in the frame and adding dotted lines to show that the values of $i and $j indicate characters in $word1 and $word2. Starting with this diagram, run the program on paper, changing the values of $i and $j during each iteration. Find and fix the second error in this function. Solution: A.5.6. 7.11 Glossary Object Something a variable can store. For now, you can use object and value interchangeably. Sequence An ordered collection of values where each value is identified by an integer index. Item One of the values in a sequence. Index An integer value used to select an item in a sequence, such as a character in a string. In Raku indices start from 0. Slice A part of a string specified by a range of indices. Empty string A string with no characters and length 0, represented by two quotation marks. Traverse To iterate through the items in a sequence, performing a similar operation on each. Search A pattern of traversal that stops when it finds what it is looking for. Counter A variable used to count something, usually initialized to zero and then incremented. Regular expressions A computing sublanguage derived from the formal language theory. 7.12. Exercises 123 Pattern A sequence of characters using a special syntax to describe from left to right the content that is intended to be matched within a target string. Regexes A pattern-matching sublanguage of Raku derived from regular expressions. Backtracking The process by which when a given attempt to match a string fails, the regex engine abandons part of the current match attempt, goes back into the string, and tries to see if it can find another route to a successful match. The backtracking process eventually stops as soon as a successful match succeeds, or ultimately when all possible match possibilities have failed. 7.12 Exercises Exercise 7.1. Write a subroutine that uses the index function in a loop to count the number of a characters in 'banana', as we did in Section 7.4. Modify it to count any letter in any word passed as arguments to the subroutine. Write another subroutine counting a given letter in a given word using the substr function. Solution: A.5.7 Exercise 7.2. The <[a..z]> character class matches any lower case character (only plain ASCII lower case characters, not Unicode characters). The following subroutine: sub is-lower (Str $char) { return so $char ~~ /^<[a..z]>$/ } should return True if its argument is an ASCII lower case letter and False otherwise. Test that it works as expected (and amend it if needed). The so function coerces the result of the regex match into a Boolean value. The following subroutines use the is-lower subroutine and are all intended to check whether a string contains any lowercase letters, but at least some of them are wrong. Analyze each subroutine by hand, determine whether it is correct, and describe what it actually does (assuming that the parameter is a string). Then test them with various input strings to check whether your analysis was correct. # ATTENTION: some of the subroutines below are wrong sub any_lowercase1(Str $string){ for $string.comb -> $char { if is-lower $char { return True; } else { return False; } } } sub any_lowercase2(Str $string){ for $string.comb -> $char { 124 Chapter 7. Strings } } if is-lower "char" { return True; } else { return False; } sub any_lowercase3(Str $string){ my $flag; for $string.comb -> $char { $flag = is-lower $char; } return $flag; } sub any_lowercase4(Str $string){ my $flag = False; for $string.comb -> $char { $flag = $flag or is-lower $char; } return $flag; } sub any_lowercase5(Str $string){ my $flag = False; for $string.comb -> $char { if is-lower $char { $flag = True; } } return $flag; } sub any_lowercase6(Str $string){ for $string.comb -> $char { if is-lower $char { return 'True'; } } return 'False'; } sub any_lowercase7(Str $string){ for $string.comb -> $char { return True if is-lower $char; } return False; } 7.12. Exercises 125 sub any_lowercase8(Str $string){ for $string.comb -> $char { return False unless is-lower $char; } return True; } sub any_lowercase9(Str $string){ for $string.comb -> $char { if not is-lower $char { return False; } return True; } } Solution: A.5.8. Exercise 7.3. A Caesar cipher is a weak form of encryption that involves rotating each letter by a fixed number of places. To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary, so A rotated by 3 is D and Z rotated by 1 is A. To rotate a word, rotate each letter by the same amount. For example, cheer rotated by 7 is jolly and melon rotated by -10 is cubed. In the movie 2001: A Space Odyssey, the ship computer is called HAL, which is IBM rotated by -1. Write a function called rotate-word that takes a string and an integer as parameters, and returns a new string that contains the letters from the original string rotated by the given amount. You might want to use the built-in functions ord, which converts a character to a numeric code (Unicode code point), and chr, which converts such numeric codes back to characters: > say 'c'.ord; 99 > say chr 99 c Letters of the alphabet are encoded in alphabetical order, so for example: > ord('c') - ord('a') 2 because 'c' is the second letter after 'a' in the alphabet. But beware: the numeric codes for upper case letters are different. Potentially offensive jokes on the internet are sometimes encoded in ROT13, which is a Caesar cipher with rotation 13. Since 13 is half the number of letters in our alphabet, applying rotation 13 twice returns the original word, so that the same procedure can be used for both encoding and decoding in rotation 13. If you are not easily offended, find and decode some of these jokes. (ROT13 is also used for other purposes, such as weakly hiding the solution to a puzzle.) Solution: A.5.9. 126 Chapter 7. Strings Chapter 8 Case Study: Word Play This chapter is intended to let you practice and consolidate the knowledge you have acquired so far, rather than introducing new concepts. To help you gain experience with programming, we will cover a case study that involves solving word puzzles by searching for words that have certain properties. For example, well find the longest palindromes in English and search for words whose letters appear in alphabetical order. And I will present another program development plan: reduction to a previously solved problem. 8.1 Reading from and Writing to Files For the exercises in this chapter, we will need our programs to read text from files. In many programming languages, this often means that we need a statement to open a file, then a statement or group of statements to read the files content, and finally a statement to close the file (although this last operation may be performed automatically in some circumstances). We are interested here in text files that are usually made of lines separated by logical new line characters; depending on your operating system, such logical new line characters consist of either one (Linux, Mac) or two (Windows) physical characters (bytes). The Raku built-in function open takes the path and name of the file as a parameter and returns a file handle (IO::Handle object) which you can use to read the file (or to write to it): my $fh = open("path/to/myfile.txt", :r); my $data = $fh.slurp-rest; $fh.close; The :r option is the file mode (read). $fh is a common name for a file handle. The file object provides methods for reading, such as slurp-rest which returns the full content of the file from the current position to the end (and the entire content of the file if weve just opened it). This is the traditional way of opening and reading files in most languages. 128 Chapter 8. Case Study: Word Play However, Rakus IO role (in simple terms, a role is a collection of related methods) offers simpler methods which can open a file and read it all in one single instruction (i.e., without having to first open a file handle and then close it): my $text = slurp "path/to/myfile.txt"; # or: my $text = "path/to/myfile.txt".IO.slurp; slurp takes care of opening and closing the file for you. We can also read the file line by line, which is very practical if each line contains a logical entity such as a record, and is especially useful for very large files that might not fit into memory: for 'path/to/hugefile.txt'.IO.lines -> $line { # Do something with $line } By default, the .lines method will remove the trailing newline characters from each line, so that you dont have to worry about them. We havent studied arrays yet, but you can also read all lines of a file into an array, with each line of the file becoming an array item. For example, you can load the myfile.txt file into the @lines array: my @lines = "myfile.txt".IO.lines; Accessing any line can then be done with the bracket operator and an index. For example, to print the first and the seventh line: say @lines[0]; say @lines[6]; To write data to a file, it is possible to open a file just as when wanting to read from it, except that the :w (write) option should be used: my $fh = open("path/to/myfile.txt", :w); $fh.say("line to be written to the file"); $fh.close; Be careful with this. If the file already existed, any existing content will be clobbered. So watch out when you want to open a file in write mode. It is also possible to open the file in append mode, using the :a option. New data will then be added after the existing content. Writing to a file can be simplified using the spurt function, which opens the file, writes the data to it, and closes it: spurt "path/to/myfile.txt", "line to be written to the file\n"; Used this way, spurt will clobber any existing content in the file. It may also be used in append mode with the :append option: spurt "path/to/myfile.txt", "line to be added\n", :append; 8.2. Reading Word Lists 8.2 129 Reading Word Lists For the exercises in this chapter we need a list of English words. There are lots of word lists available on the web, but one of the most suitable for our purpose is one of the word lists collected and contributed to the public domain by Grady Ward as part of the Moby lexicon project (see http://wikipedia.org/wiki/Moby_Project). It is a list of 113,809 official crosswords; that is, words that are considered valid in crossword puzzles and other word games. In the Moby collection, the filename is 113809of.fic; you can download a copy, with the simpler name words.txt, from https://github.com/LaurentRosenfeld/think_raku/ tree/master/Supplementary/words.txt. This file is in plain text (with each word of the list on its own line), so you can open it with a text editor, but you can also read it from Raku. Lets do so in the interactive mode (with the REPL): > my $fh = open("words.txt", :r); IO::Handle(opened, at octet 0) > my $line = get $fh; aa > say "<<$line>>"; < > The get function reads one line from the file handle. The first word in this particular list is aa (a kind of lava). Printing the $line variable between angle brackets within a string shows us that the get function removed implicitly the trailing newline characters, in this case a \r\n (carriage return and newline) character combination, since this file was apparently prepared under Windows. The file handle keeps track of what has been read from the file and what it should read next, so if you call get again, you obtain the next line: > my $line = get $fh; aah The next word is aah, which is a perfectly legitimate word, so stop looking at me like that. This is good and fine if we want to explore the first few lines of the words.txt file, but we are not going to read the 113 k-lines of the file this way. We need a loop to do it for us. We could insert the above get instruction into a while loop, but we have seen above an easier and more efficient way of doing it using a for loop and the IO.lines method, without the hassle of having to open or close the file: for 'words.txt'.IO.lines -> $line { say $line; } This code reads the file line by line, and prints each line to the screen. Well soon do more interesting things than just displaying the lines on the screen. 130 Chapter 8. Case Study: Word Play 8.3 Exercises This case study consists mainly of exercises and solutions to them within the body of the chapter because solving the exercises is the main teaching material of this chapter. Therefore, solutions to these exercises are in the following sections of this chapter, not in the appendix. You should at least attempt each one before you read the solutions. Exercise 8.1. Write a program that reads words.txt and prints only the words with more than 20 characters. Exercise 8.2. In 1939 Ernest Vincent Wright published a 50,000-word novel called Gadsby that does not contain the letter e. Since e is the most common letter in English, thats not easy to do. In fact, it is difficult to construct a solitary thought without using that most common letter. Such a writing in which one letter is avoided is sometimes called a lipogram. Write a subroutine called has-no-e that returns True if the given word doesnt have the letter e in it. Modify your program from the previous exercise to print only the words that have no e and compute the percentage of the words in the list that have no e. (The word dictionary we are using, words.txt, is entirely in lower-case letters, so you dont need to worry about any uppercase E.) Exercise 8.3. Write a subroutine named avoids that takes a word and a string of forbidden letters, and that returns True if the word doesnt use any of the forbidden letters. Next, modify your program to prompt the user to enter a string of forbidden letters and then print the number of words that dont contain any of them. Can you find a combination of five forbidden letters that excludes the smallest number of words? Exercise 8.4. Write a subroutine named uses-only that takes a word and a string of letters, and that returns True if the word contains only letters in the list. Can you make a sentence using only the letters acefhlo? Other than Hoe alfalfa? Exercise 8.5. Write a subroutine named uses-all that takes a word and a string of required letters, and returns True if the word uses all the required letters at least once. How many words are there that use all the vowels aeiou? How about aeiouy? Exercise 8.6. Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok). How many abecedarian words are there? 8.4 Search Most of the exercises in the previous section have something in common; they can be solved with the search pattern (and the index function we saw in Section 7.2.2 (p. 100). Most can also be solved using regexes. 8.4.1 Words Longer Than 20 Characters (Solution) The solution to the simplest exercise printing all the words of words.txt that are longer than 20 characters is: for 'words.txt'.IO.lines -> $line { say $line if $line.chars > 20 } 8.4. Search 131 Because the code is so simple, this is a typical example of a possible and useful one-liner (as described in Section 2.5). Assuming you want to know the words that are longer than 20 characters, you dont even need to write a script, save it, and run it. You can simply type this at your operating system prompt: $ raku -n -e '$_.say if $_.chars > 20;' words.txt The -e option tells Raku that the script to be run comes next on the command line between quotation marks. The -n asks Raku to read line by line the file after the end of the command line, to store each line in the $_ topical variable, and to apply the content of the script to each line. And the one-liner script is just printing the content of $_ if its length is greater than 20. To simplify a bit, the two options -n and -e may be grouped together as raku -ne. In addition, the $_ topical variable can be omitted in method calls (in other words, if a method has no invocant, the invocant will be defaulted to $_). Finally, the trailing semi-colon may also be removed. The one-liner above can thus be made somewhat simpler and shorter: $ raku -ne '.say if .chars > 20' words.txt Remember that, if youre trying this under Windows, you need to replace the single quotes with double quotes (and vice-versa if the scripts itself contains double quotes): C:\Users\Laurent>raku -ne ".say if .chars > 20" words.txt 8.4.2 Words with No e (Solution) A subroutine that returns True for words that have no e (Exercise 8.2) is also quite straight forward: sub has-no-e (Str $word) { return True unless defined index $word, "e"; return False; } The subroutine simply returns True if the index function did not find any e in the word received as a parameter and False otherwise. Note that this works correctly because the word list used words.txt) is entirely in lowercase letters. The above subroutine would need to be modified if it might be called with words containing uppercase letters. Since the defined function returns a Boolean value, we could shorten our subroutine to this: sub has-no-e (Str $word) { not defined index $word, "e"; } We could also have used a regex for testing the presence of a e on the second line of this subroutine: 132 Chapter 8. Case Study: Word Play return True unless $word ~~ /e/; This fairly concise syntax is appealing, but when looking for an exact literal match, the index function is likely to be slightly more efficient (faster) than a regex. Looking for the words without e in our word list and counting them is not very difficult: sub has-no-e (Str $word) { not defined index $word, "e"; } my $total-count = 0; my $count-no-e = 0; for 'words.txt'.IO.lines -> $line { $total-count++; if has-no-e $line { $count-no-e++; say $line; } } say "=" x 24; say "Total word count: $total-count"; say "Words without 'e': $count-no-e"; printf "Percentage of words without 'e': %.2f %%\n", 100 * $count-no-e / $total-count; The above program will display the following at the end of its output: ======================== Total word count: 113809 Words without 'e': 37641 Percentage of words without 'e': 33.07 % So, less than one third of the words of our list have no e. 8.4.3 Avoiding Other Letters (Solution) The avoids subroutine is a more general version of has_no_e, but it has the same structure: sub avoids (Str $word, Str $forbidden) { for 0..$forbidden.chars - 1 -> $idx { my $letter = substr $forbidden, $idx, 1; return False if defined index $word, $letter; } True; } We can return False as soon as we find a forbidden letter; if we get to the end of the loop, we return True. Since a subroutine returns the last evaluated expression, we dont need to explicitly use a return True statement in the last code line above. I used this feature 8.4. Search 133 here as an example; you might find it clearer to explicitly return values, except perhaps for very simple one-line subroutines. Note that we have here implicitly two nested loops. We could reverse the outer and the inner loops: sub avoids (Str $word, Str $forbidden) { for 0..$word.chars - 1 -> $idx { my $letter = substr $word, $idx, 1; return False if defined index $forbidden, $letter; } True; } The main code calling the above subroutine is similar to the code calling has-no-e and might look like this: my $total-count = 0; my $count-no-forbidden = 0; for 'words.txt'.IO.lines -> $line { $total-count++; $count-no-forbidden++ if avoids $line, "eiou"; } say "=" x 24; say "Total word count: $total-count"; say "Words without forbidden: $count-no-forbidden"; printf "Percentage of words with no forbidden letter: %.2f %%\n", 100 * $count-no-forbidden / $total-count; 8.4.4 Using Only Some Letters (Solution) uses-only is similar to our avoids subroutine except that the sense of the condition is reversed: sub uses-only (Str $word, Str $available) { for 0..$word.chars - 1 -> $idx { my $letter = substr $word, $idx, 1; return False unless defined index $available, $letter; } True; } Instead of a list of forbidden letters, we have a list of available letters. If we find a letter in $word that is not in $available, we can return False. And we return True if we reach the loop end. 134 Chapter 8. Case Study: Word Play 8.4.5 Using All Letters of a List (Solution) uses-all is similar to the previous two subroutines, except that we reverse the role of the word and the string of letters: sub uses-all(Str $word, Str $required) { for 0..$required.chars - 1 -> $idx { my $letter = substr $word, $idx, 1; return False unless defined index $word, $letter; } return True; } Instead of traversing the letters in $word, the loop traverses the required letters. If any of the required letters do not appear in the word, we can return False. If you were really thinking like a computer scientist, you would have recognized that uses-all was an instance of a previously solved problem in reverse: if word A uses all letters of word B, then word B uses only letters of word A. So, we can call the uses-only subroutine and write: sub uses-all ($word, $required) { return uses-only $required, $word; } This is an example of a program development plan called reduction to a previously solved problem, which means that you recognize the problem you are working on as an instance of a solved problem and apply an existing solution. 8.4.6 Alphabetic Order (Solution) For is_abecedarian we have to compare adjacent letters. Each time in our for loop, we define one letter as our current letter and compare it with the previous one: sub is_abecedarian ($word) { for 1..$word.chars - 1 -> $idx { my $curr-letter = substr $word, $idx, 1; return False if $curr-letter lt substr $word, $idx - 1, 1; } return True } An alternative is to use recursion: sub is-abecedarian (Str $word) { return True if $word.chars <= 1; return False if substr($word, 0, 1) gt substr($word, 1, 1); return is-abecedarian substr $word, 1; } Another option is to use a while loop: 8.4. Search 135 sub is_abecedarian (Str $word): my $i = 0; while $i < $word.chars -1 { if substr($word, $i, 1) gt substr ($word, $i+1, 1) { return False; } $i++; } return True; } The loop starts at $i=0 and ends when i=$word.chars -1. Each time through the loop, it compares the ith character (which you can think of as the current character) to the i + 1th character (which you can think of as the next). If the next character is less than (alphabetically before) the current one, then we have discovered a break in the abecedarian trend, and we return False. If we get to the end of the loop without finding a fault, then the word passes the test. To convince yourself that the loop ends correctly, consider an example like 'flossy'. The length of the word is 6, so the last time the loop runs is when $i is 4, which is the index of the second-to-last character. On the last iteration, it compares the second-to-last character (the second s) to the last (the y), which is what we want. 8.4.7 Another Example of Reduction to a Previously Solved Problem Here is a version of is_palindrome (see Exercise 5.3) that uses two indices; one starts at the beginning and goes up, while the other starts at the end and goes down: sub one-char (Str $string, $idx) { return substr $string, $idx, 1; } sub is-palindrome (Str $word) { my $i = 0; my $j = $word.chars - 1; } while $i < $j { return False if one-char($word, $i) ne one-char($word, $j); $i++; $j--; } return True; Or we could reduce to a previously solved problem and write: sub is-palindrome (Str $word) { return is-reverse($word, $word) } using is-reverse from Section 7.10 (but you should probably choose the corrected version of the is-reversed subroutine given in the appendix: see Subsection A.5.6). 136 8.5 Chapter 8. Case Study: Word Play Debugging Testing programs is hard. The functions in this chapter are relatively easy to test because you can check the results by hand. Even so, it is somewhere between difficult and impossible to choose a set of words that test for all possible errors. Taking has_no_e as an example, there are two obvious cases to check: words that have an e should return False, and words that dont should return True. You should have no trouble coming up with one of each. Within each case, there are some less obvious subcases. Among the words that have an e, you should test words with an e at the beginning, the end, and somewhere in the middle. You should test long words, short words, and very short words, like an empty string. The empty string is an example of a special case, which is one of the nonobvious cases where errors often lurk. In addition to the test cases you generate, you can also test your program with a word list like words.txt. By scanning the output, you might be able to catch errors, but be careful: you might catch one kind of error (words that should not be included, but are) and not another (words that should be included, but arent). In general, testing can help you find bugs, but it is not easy to generate a good set of test cases, and even if you do, you cant be sure your program is correct. According to a legendary computer scientist: Program testing can be used to show the presence of bugs, but never to show their absence! Edsger W. Dijkstra 8.6 Glossary File object A value that represents an open file. Reduction to a previously solved problem A way of solving a problem by expressing it as an instance of a previously solved problem. Special case A test case that is atypical or nonobvious (and less likely to be handled correctly). The expressions edge case and corner case convey more or less the same idea. 8.7 Exercises Exercise 8.7. This question is based on a Puzzler that was broadcast on the radio program Car Talk (http: // www. cartalk. com/ content/ puzzlers ): Give me a word with three consecutive double letters. Ill give you a couple of words that almost qualify, but dont. For example, the word committee, c-o-m-m-i-t-t-e-e. It would be great except for the i that sneaks in there. Or Mississippi: M-i-s-s-i-s-s-ip-p-i. If you could take out those is it would work. But there is a word that has three consecutive pairs of letters and to the best of my knowledge this may be the only word. Of course there are probably 500 more but I can only think of one. What is the word? 8.7. Exercises 137 Write a program to find it. Solution: A.6.1. Exercise 8.8. Heres another Car Talk Puzzler (http: // www. cartalk. com/ content/ puzzlers ): I was driving on the highway the other day and I happened to notice my odometer. Like most odometers, it shows six digits, in whole miles only. So, if my car had 300,000 miles, for example, Id see 3-0-0-0-0-0. Now, what I saw that day was very interesting. I noticed that the last 4 digits were palindromic; that is, they read the same forward as backward. For example, 5-4-4-5 is a palindrome, so my odometer could have read 3-1-5-4-4-5. One mile later, the last 5 numbers were palindromic. For example, it could have read 3-6-5-4-5-6. One mile after that, the middle 4 out of 6 numbers were palindromic. And you ready for this? One mile later, all 6 were palindromic! The question is, what was on the odometer when I first looked? Write a program that tests all the six-digit numbers and prints any numbers that satisfy these requirements. Solution: A.6.2. Exercise 8.9. Heres another Car Talk Puzzler you can solve with a search (http: // www. cartalk. com/ content/ puzzlers ): Recently I had a visit with my mom and we realized that the two digits that make up my age when reversed resulted in her age. For example, if shes 73, Im 37. We wondered how often this has happened over the years but we got sidetracked with other topics and we never came up with an answer. When I got home I figured out that the digits of our ages have been reversible six times so far. I also figured out that if were lucky it would happen again in a few years, and if were really lucky it would happen one more time after that. In other words, it would have happened 8 times over all. So the question is, how old am I now? Write a Raku program that searches for solutions to this Puzzler. Hint: you might find the string formatting method sprintf useful. Solution: A.6.3. 138 Chapter 8. Case Study: Word Play Chapter 9 Arrays and Lists This chapter presents some of Rakus most useful built-in types, arrays and lists. 9.1 Lists and Arrays Are Sequences Like strings, lists and arrays are sequences of values. In a string, the values are characters; in a list or in an array, they can be any type. The values in a list or in an array are called elements or sometimes items. There are several important differences between lists and arrays. The main ones are that lists are ordered and immutable collections of items: you cant change the number of items in a list and you cant change the individual items either. Arrays, by contrast, are variables and are generally mutable: you can add elements to an array, or remove elements from it. And you can access the individual elements of an array and modify them. For this to be possible, arrays usually have a name (as do other variables), although some arrays are anonymous, which means that they have no name, but have some other ways of accessing them. A list is also ephemeral (unless it is assigned to a variable or some other thing): it ceases to exist as soon as it has been used, usually as soon as the program control flow goes to the next code line. An array, on the other hand, has some form of persistence: you may be able to use it somewhere else in the program if the variable containing it is still within scope. There are several ways to create a new list; the simplest is to enumerate its values, separated by commas: > 3, 4, 5 (3 4 5) > say (3, 4, 5).WHAT; (List) say $_ for 1, 2, 3; 1 2 3 140 Chapter 9. Arrays and Lists You dont need parentheses to create a list, but they are often useful to delimit it, i.e., to stipulate where it starts and where it ends, and, in some cases, to override precedence. We used lists earlier in this book. If we write: > print "$_ " for 1, 3, 5, 9, "\n"; 1 3 5 9 > > print "$_ " for 1..10; 1 2 3 4 5 6 7 8 9 10 > we are basically creating and using a list of integers (from the standpoint of the type hierarchy of Raku; this observation is not entirely accurate technically for the second example, since 1..10 has a Range type, and it gets transformed into a Seq type, but this approximation is good enough for our purposes here). Arrays are variables whose names start with the sigil @. Named arrays need to be declared before they are used, just as any other variable weve seen so far (except the topical variable, $_). One of the easiest ways to create an array is to assign a list to it: > my @odd_digits = 1, 3, 5, 7, 9; [1 3 5 7 9] > say @odd_digits.WHAT; (Array) > my @single_digit_numbers = 0..9; [0 1 2 3 4 5 6 7 8 9] Under the Raku REPL, an array is displayed between square brackets ([ and ]), while lists are displayed between round parentheses. If the items dont contain any space characters, it is quite handy to construct a list (and assign it to an array if needed) using the <...> quote-word operator: > my [mon > my [sat @weekdays = ; tue wed thu fri] @weekend = ; sun] The advantage of this construction is that there is no need to separate the items with commas and no need to insert them between quotes when the items are strings. Basically, the quote-word operator breaks up its content on whitespace and returns a list of words, which can then be used in a loop or assigned to an array as in the example above. Most of the rest of this chapter will be devoted to arrays rather than lists, but keep in mind that many of the array functions and operators we will study here also work on lists (at least most of those that would not violate the immutability property of lists). The items of an array (or a list) dont need to be of the same type: > my @heterogeneous-array = 1, 2.3, pi, "str", (1, 2, 4); [1 2.3 3.14159265358979 str (1 2 4)] 9.2. Arrays Are Mutable 141 Here, the array is composed of an integer, a rational, a float (Num type), a string, and a list of three integers. It may not be advisable for the sake of the developers mental sanity to use an array with such wildly heterogeneous items, but Raku will not complain about that: it is up to you to make sense of your data. The array above even contains a list of items. If you iterate over the elements of this array for example with a for loop statement, this list will arrive as one distinct element; it will not get flattened as three elements of the array. Similarly, elems is a method to count the number of items of an array (or of a list). Using it on the above array produces the following result: > say @heterogeneous-array.elems; 5 As you can see, the (1, 2, 4) list counts as one single array element. A list within another list is nested. An array that contains no elements is called an empty array; you can create one with empty parentheses, (): > my @empty = (); [] This code is really assigning an empty list to the array. But this syntax is usually not needed when creating a new empty array, since just declaring an array without defining it has the same effect: > my @empty; [] So using the empty parentheses (i.e., assigning an empty list) would be needed essentially for resetting an existing array to an empty array. 9.2 Arrays Are Mutable The syntax for accessing the elements of an array or a list uses the square brackets operator. The expression inside the brackets specifies the index or subscript, which can be a literal integer (or some value that can be coerced into an integer), a variable containing a numerical value, a list or a range of numerical values, an expression or a piece of code returning a numerical value, etc. Indices are offsets compared to the beginning of the array or the list (much in the same way as the values returned by the index function on strings), so that they start at 0. Thus, the first item of an array has the index 0, the second item the index 1, and so on: say [1]; # -> sun my @weekdays = ; say "The third day is @weekdays[2]"; (accessing a list item) # assigning an array # -> The third day is wed You may also use ranges or lists of indices to access slices of an array or a list: 142 Chapter 9. Arrays and Lists > my @even-digits = 0, 2, 4, 6, 8; [0 2 4 6 8] > my @small-even_digits = @even-digits[0..2]; [0 2 4] > my @min-max-even-digits = @even-digits[0, 4] [0 8] If you need a slice in the opposite order, you can use the reverse function to reverse the range: > my @reverse-small-even_digits = @even-digits[reverse 0..2]; [4 2 0] or reverse the data returned by the slice expression: > my @reverse-small-even_digits = reverse @even-digits[0..2]; [4 2 0] Unlike lists, arrays are mutable. When the bracket operator appears after an array on the left side of an assignment, it identifies the element of the array that will be assigned: > my @even-digits = 0, 2, 2, 6, 8; # Oops, error on the second 2 [0 2 2 6 8] > @even-digits[2] = 4; # fixing the faulty third digit 4 > say @even-digits [0 2 4 6 8] The third element of even-digits, which was (presumably by mistake) 2, is now 4. If the index corresponds to an item which does not exist yet in the array, the array will be expanded to include the new element: > my @odds = 1, 3, 5; [1 3 5] > @odds[3] = 7; 7 > say @odds; [1 3 5 7] The elems function or method returns the number of elements of an array. The end function or method returns the index of the last element of an array: my @nums = 1..5; say @nums.elems; say elems @nums; say @nums.end; # # # # -> -> -> -> [1 2 3 4 5] 5 5 4 The end method returns the result of the elems method minus one because, since indices start at 0, the index of the last element is one less than the number of elements. The unique function or method returns a sequence of unique elements of the input list or array (i.e., it returns the original list without any duplicate values): 9.3. Adding New Elements to an Array or Removing Some 143 > say < a b d c a f d g>.unique; (a b d c f g) If you know that the input is sorted (and that, therefore, duplicates are adjacent), use the squish function instead of unique, as this is likely to be more efficient. The squish function removes adjacent duplicates. To know whether two arrays are identical (structurally the same, with the same type and same values), use the eqv equivalence operator. To know whether they just contain the same elements, use the ~~ smart match operator. Between two arrays or lists, the == numeric equality operator will return True if the arrays have the same number of elements and False otherwise, because == coerces its arguments to numeric type, so that it compares the number of elements: > my @even1 = 0, 2, 4, 6, 8; [0 2 4 6 8] > my @even2 = reverse 8, 6, 4, 2, [0 2 4 6 8] > say @even1 eqv @even2; True > say <1 2 3 4 5> eqv 1..5; False > say <1 2 3 4 5> ~~ 1..5; True > my @array = 1..5; [1 2 3 4 5] > say <1 2 3 4 5> ~~ @array; True > say <1 2 3 4 6> ~~ @array; False > say <1 2 3 4 5> == <5 6 7 8 9>; True 0; # same items, structurally the same # same items, structurally different # same items, True # same elements, True # not the same elements # compares the numbers of items The <1 2 3 4 5> eqv 1..5 statement returns False because, although they have the same items, the arguments are structurally different entities (one is a list and the other one a range). 9.3 Adding New Elements to an Array or Removing Some Weve just seen that assigning an item to an index that does not exists yet will expand the array. There are other ways of expanding an array. Raku has operators to add elements to, or remove one element from, an array: shift: removes the first item of an array and returns it; pop: removes the last item of an array and returns it; unshift: adds an item or a list of items to the beginning of an array; push: adds an item or a list of items to the end of an array; 144 Chapter 9. Arrays and Lists These are a few examples for each: > my @numbers = <2 4 6 7>; [2 4 6 7] > push @numbers, 8, 9; [2 4 6 7 8 9] > unshift @numbers, 0, 1; [0 1 2 4 6 7 8 9] > my $num = shift @numbers 0 > $num = pop @numbers 9 > say @numbers [1 2 4 6 7 8] As you might expect by now, these routines also come with a method invocation syntax. For example: > my @numbers = <2 4 6 7>; [2 4 6 7] > @numbers.push(8, 9) [2 4 6 7 8 9] Note, however, that if you push or unshift an array onto another array, youll get something different than what you might expect: > my @numbers = <2 4 6 7>; [2 4 6 7] > my @add-array = 8, 10; [8 10] > @numbers.push(@add-array); [2 4 6 7 [8 10]] As you can see, when @add-array is added as an entity to the @numbers array, @add-array becomes the new last item of the original array. If you want to add the items of @add-array to the original array, you may use the append method instead of push: > my @numbers = <2 4 6 7>; [2 4 6 7] > @numbers.append(@add-array); [2 4 6 7 8 10] Or you can use the | prefix operator to flatten the added array into a list of arguments: > my @numbers = <2 4 6 7>; [2 4 6 7] > @numbers.push(|@add-array); [2 4 6 7 8 10] There is also a prepend method that can replace unshift to add individual items of an array at the beginning of an existing array (instead of adding the array as a single entity). 9.4. Stacks and Queues 9.4 145 Stacks and Queues Stacks and queues are very commonly used data structures in computer science. A stack is a last in / first out (LIFO) data structure. Think of piled-up plates. When you put a clean plate onto the stack, you usually put it on top; when you take out one, you also take it from the top. So the first plate that you take is the last one that you added. A CS stack implements the same idea: you use it when the first piece of data you need from a data structure is the last one you added. A queue, by contrast, is a first in / first out (FIFO) data structure. This is the idea of people standing in a line waiting to pay at the supermarket. The first person that will be served is the first person who entered the queue. A stack may be implemented with an array and the push and pop functions, which respectively add an item (or several) at the end of an array and take one from the end of the array. This is a somewhat simplistic implementation of a stack: sub put-in-stack (@stack, $new_item) { push @stack, $new_item; } sub take-from-stack (@stack) { my $item = pop @stack; return $item; } my @a-stack = 1, 2, 3, 4, 5; put-in-stack @a-stack, 6; say @a-stack; say take-from-stack @a-stack for 1..3; This example will print this: [1 2 3 4 5 6] 6 5 4 This stack is simplistic because, at the very least, a more robust implementation should do something sensible when you try to take-from-stack from an empty stack. It would also be wise to add signatures to the subroutines. In addition, you might want to put-in-stack more than one element in one go. Take a look at the solution to the exercise on queues below (Subsection A.7.1) to figure out on how this stack may be improved. You could obtain the same stack features using the unshift and shift functions instead of push and pop. The items will be added at the beginning of the array and taken from the beginning, but you will still have the LIFO behavior. As an exercise, try to implement a FIFO queue on the same model. Hint: you probably want to use an array and the unshift and pop functions (or the push and shift functions). Solution: A.7.1. 146 9.5 Chapter 9. Arrays and Lists Other Ways to Modify an Array The shift and pop functions remove respectively the first and the last item of an array and return that item. It is possible to do almost the same operation on any item of an array, using the delete adverb: my @fruit = ; my $removed = @fruit[2]:delete; say $removed; # -> pear say @fruit; # -> [apple banana (Any) cherry pineapple orange] Notice that the third element (pear) is removed and returned, but the array is not reorganized; the operation leaves a sort of empty slot, an undefined item, in the middle of the array. The colon (:) syntax used here is the operator for an adverb (we discussed adverbs in Section 7.5 about regexes); for the time being, you may think of it as a kind of special method operating on one element of an item collection. We have seen how to use array slices to retrieve several items of an array or a list at a time. The same slice syntax can also be used on the left side of an assignment to modify some elements of an array: my @digits = <1 2 3 6 5 4 7 8 9> @digits[2..4] = 4, 5, 6 say @digits; # -> [1 2 4 5 6 4 7 8 9] Of course, you cant do this with lists, since, as you remember, they are immutable. The splice function may be regarded as the Swiss Army knife of arrays. It can add, remove, and return one or several items to or from an array. The general syntax is as follows: my @out_array = splice @array, $start, $num_elems, @replacement; The arguments for splice are the input array, the index of the first element on which to make changes, the number of elements to be affected by the operation, and a list of replacements for the elements to be removed1 . For example, to perform the slice assignment shown just above, it is possible to do this: my @digits = <1 2 3 6 5 4 7 8 9> my @removed_digits = splice @digits, 3, 3, 4, 5, 6; say @removed_digits; # -> [6 5 4] say @digits; # -> [1 2 3 4 5 6 7 8 9] Here, the splice statement removed three elements (6, 5, 4) and replaced them with the replacement arguments (4, 5, 6). It also returned the removed items into @removed_digits. The number of replacements does not need to be the same as the number of removed items, in which case the array size will grow or shrink. For example, if no replacement is provided, then splice will just remove and return the required number of elements and the array size will be reduced by the same number: 1 Notice that the splice function on arrays has almost the same syntax as the substr function on strings. This may make it easier to understand them and remember their syntax. 9.5. Other Ways to Modify an Array 147 my @digits = 1..9; my @removed_digits = splice @digits, 3, 2; say @removed_digits; # -> [4 5] say @digits; # -> [1 2 3 6 7 8 9] Conversely, if the number of elements to be removed is zero, no element will be removed, an empty array will be returned, and the elements in the replacement list will be added in the right place: my @digits = <1 2 3 6 4 7 8 9>; my @removed_digits = splice @digits, 3, 0, 42; say @removed_digits; # -> [] say @digits; # -> [1 2 3 42 6 4 7 8 9] Assuming the shift function did not exist in Raku, you could write a my-shift subroutine to simulate it: sub my-shift (@array) { my @result = splice @array, 0, 1; return @result[0]; } my @letters = 'a'..'j'; my $letter = my-shift @letters; say $letter; # -> a say @letters; # -> [b c d e f g h i j] We might raise an exception if the array passed to my-shift is empty. This could be done by modifying the subroutine as follows: sub my-shift (@array) { die "Cannot my-shift from an empty array" unless @array; my @result = splice @array, 0, 1; return @result[0]; } or by adding a nonempty constraint on the array in the subroutine signature: sub my-shift (@array where @array > 0) { my @result = splice @array, 0, 1; return @result[0]; } The @array > 0 expression evaluates to True if the number of elements of the array is more than 0, i.e., if the array is not empty. It is equivalent to @array.elems > 0. As an exercise, write subroutines using splice to simulate the pop, unshift, push, and delete built-ins. Solution: A.7.2. 148 9.6 Chapter 9. Arrays and Lists Traversing a List The most common way to traverse the elements of a list or an array is with a for loop. The syntax for an array is the same as what we have already seen in earlier chapters for lists: my @colors = ; for @colors -> $color { say $color; } This works well if you only need to read the elements of the list. But if you want to write or update the elements of an array, you need a doubly pointy block. For example, you might use the tc (title case) function to capitalize the first letter of each word of the array: my @colors = ; for @colors <-> $color {$color = tc $color}; say @colors; # -> [Red Orange Yellow Green Blue Indigo Violet] Here the $color loop variable is a read-and-write alias on the arrays items, so that changes made to this alias will be reflected in the array. This works well with arrays, but would not work with lists, which are immutable. You would get an error with a list: > for <-> $color { $color = tc $color} Parameter '$color' expected a writable container, but got Str value... You may also use the syntax of a for loop with the $_ topical variable. For example, this uses the uc (upper case) function to capitalize each word of the previous array: for @colors { $_ = $_.uc } say @colors; # -> [RED ORANGE YELLOW GREEN BLUE INDIGO VIOLET] Sometimes, you want to traverse an array and need to know the index of the elements you are visiting. A common way to do that is to use the .. range operator to iterate on the indices. For instance, to print the index and the value of each element of an array: for 0..@colors.end -> $idx { say "$idx @colors[$idx]"; } This is useful, for example, for traversing two (or more) arrays in parallel: my @letters = 'a'..'e'; my @numbers = 1..5; for 0..@letters.end -> $idx { say "@letters[$idx] -> @numbers[$idx]"; } This will print: 9.7. New Looping Constructs a b c d e -> -> -> -> -> 149 1 2 3 4 5 You dont really need to specify the index range yourself, as the keys function will return a list of indices for the array or the list: for keys @colors -> $idx { say "$idx @colors[$idx]"; } Another way to iterate over the indices and values of an array is the kv (keys values) function or method, which returns the index and value of each array item: for @letters.kv -> $idx, $val { say "$idx $val"; } In list context, @letters.kv simply returns an interleaved sequence of indexes and values: my @letters = 'a'..'e'; say @letters.kv; # -> (0 a 1 b 2 c 3 d 4 e) It is the pointy block with two iteration variables that makes it possible to process both an index and a value at each step of the loop. You can of course have more than two iteration variables if needed. 9.7 New Looping Constructs Since the subject of this chapter is arrays and lists, it is probably the right time to briefly study two looping constructs that I had left aside so far. The first one uses the same for keyword as above, but with a different syntax for the iteration variable(s): my @letters = 'a'..'e'; for @letters { say $^a-letter; } The ^ in the $^a-letter variable is called a twigil, i.e., sort of a secondary sigil. When there is a twigil, the first symbol (here, the $ sign) has the same meaning as usual sigils (here, it denotes a scalar variable), and the second one (here, ^) extends the variable description and usually modifies its scope. In this specific case, the second character states that the $^a-letter variable is a placeholder parameter or a self-declared positional parameter. This is a positional parameter of the current block that needs not be declared in the signature. If the block uses more than one placeholder, they are associated to the input according to their lexicographic (alphabetic) order: 150 Chapter 9. Arrays and Lists my @letters = 'a'..'e'; for @letters.kv { say "$^a -> $^b"; } This will print: 0 1 2 3 4 -> -> -> -> -> a b c d e As seen just above, the kv function returns an interleaved sequence of indexes and values. Since $^a comes before $^b in the alphabetic order, $^a will be bound to the index and $^b with the value for each pair of the input. Placeholders can also be used for subroutines: > sub divide { $^first / $^second } sub divide ($first, $second) { #`(Sub|230787048) ... } > divide 6, 4 1.5 These placeholders arent used very often for simply traversing arrays, but we will see later how they are very useful in cases where is would be quite unpractical to have to declare the parameters. The second new looping construct I want to introduce here uses the loop keyword and is similar to the C-style for loop (i.e., the loop of the C programming language). In this type of loop, you declare between a pair of parentheses three expressions separated by semi-colons: the iteration variables initial value, the condition on which the loop should terminate, and the change made to the iteration variable on each iteration: loop (my $i = 0; $i < 5; $i++) { say $i, " -> " ~ @letters[$i]; } For most common loops, the for loops seen earlier are easier to write and usually more efficient than this construct. This special loop construct should probably be used only when the exit condition or the change made to the iteration variable is quite unusual and would be difficult to express in a regular for loop. As an exception, the loop construct with no three-part specification is quite common and even idiomatic for making an infinite loop: loop { # do something # last if ... } 9.8. Map, Filter and Reduce 9.8 151 Map, Filter and Reduce When traversing the elements of an array (or a list) so far, we have processed so far one item at a time with a loop. We will now study ways to process all the elements in one go. 9.8.1 Reducing a List to a Value To add up all the numbers in a list, you can use a for loop like this: sub add_all (@numbers) { my $total = 0; for @numbers -> $x { $total += $x; } return $total; } $total is initialized to 0. Each time through the loop, $x gets one element from the list and is added to $total. As the loop runs, total accumulates the sum of the elements; a variable used this way is sometimes called an accumulator. An operation like this that combines a sequence of elements into a single value is often called a reduction operation because its effect is to reduce all the items to one element (this is also sometimes called folding in some other programming languages). These ideas are derived from functional programming languages such as LISP (whose name stands for list processing). Raku has a reduce function, which generates a single "combined" value from a list of values, by iteratively applying to each item of a list a function that knows how to combine two values. Using the reduce function to compute the sum of the first ten numbers might look like this: > my $sum = reduce { $^a + $^b }, 1..10; 55 Remember the factorial function of Section 4.10? It used a for loop to compute the product of the n first integers up to a limit. It could be rewritten as follows using the reduce function: sub factorial (Int $num) { return reduce { $^a * $^b }, 1..$num; } say factorial 10; # -> 3628800 In fact, the code to compute the factorial is so short with the reduce function that it may be argued that it has become unnecessary to write a subroutine for that. You could just inline the code: my $fact10 = reduce { $^a * $^b }, 1..10; # -> 3628800 We can do many more powerful things with that, but well come back to that later, as it requires a few syntactic features that we havent seen yet. 152 Chapter 9. Arrays and Lists 9.8.2 The Reduction Metaoperator Raku also has a reduction operator, or rather a reduction metaoperator. An operator usually works on variables or values; a metaoperator acts on other operators. Given a list and an operator, the [...] metaoperator iteratively applies the operator to all the values of the list to produce a single value. For example, the following also prints the sum of all the elements of a list: say [+] 1, 2, 3, 4; # -> 10 This basically takes the first two values, adds them up, and adds the result to the next value, and so on. Actually, there is a form of this operator, with a backslash before the operator, which also returns the intermediate results: say [\+] 1, 2, 3, 4; # -> (1 3 6 10) This metaoperator can be used to transform basically any associative infix operator2 into a list operator returning a single value. The factorial function can now be rewritten as: sub fact(Int $x){ [*] 1..$x; } my $factorial = fact(10); # -> 3628800 The reduction metaoperator can also be used with relational operators to check whether the elements of an array or a list are in the correct numerical or alphabetical order: say [<] 3, 5, 7; say [<] 3, 5, 7, 6; say [lt] ; 9.8.3 # -> True # -> False # -> True Mapping a List to Another List Sometimes you want to traverse one list while building another. For example, the following function takes a list of strings and returns a new list that contains capitalized strings: sub capitalize_all(@words){ my @result; push @result, $_.uc for @words; return @result; } my @lc_words = ; my @all_caps = capitalize_all(@lc_words); # -> [ONE TWO THREE] @result is declared as an empty array; each time through the loop, we add the next element. So @result is another kind of accumulator. An operation like capitalize_all is sometimes called a map because it maps a function (in this case the uc method) to each of the elements in a sequence. Raku has a map function that makes it possible to do that in just one statement: 2 An infix operator is an operator that is placed between its two operands. 9.8. Map, Filter and Reduce 153 my @lc_words = ; my @all_caps = map { .uc }, @lc_words; # -> [ONE TWO THREE] Here, the map function applies the uc method to each item of the @lc_words array and returns them into the @all_caps array. More precisely, the map function iteratively assigns each item of the @lc_words array to the $_ topical variable, applies the code block following the map keyword to $_ in order to create new values, and returns a list of these new values. To generate a list of even numbers between 1 and 10, we might use the range operator to generate numbers between 1 and 5 and use map to multiply them by two: my @evens = map { $_ * 2 }, 1..5; # -> [2 4 6 8 10] Instead of using the $_ topical variable, we might also use a pointy block syntax with an explicit iteration variable: my @evens = map -> $num { $num * 2 }, 1..5; # -> [2 4 6 8 10] or an anonymous block with a placeholder variable: my @evens = map { $^num * 2 }, 1..5; # -> [2 4 6 8 10] Instead of a code block, the first argument to map can be a code reference (a subroutine reference): sub double-sq-root-plus-one (Numeric $x) { 1 + 2 * sqrt $x; } my @results = map &double-sq-root-plus-one, 4, 16, 42; say @results; # -> [5 9 13.9614813968157] The subroutine name needs to be prefixed with the ampersand sigil to make clear that it is a parameter to map and not a direct call of the subroutine. If the name of the array on the left side and on the right side of the assignment is the same, then the modification seems to be made in place, i.e., it appears as if the original array is modified in the process. This is an immensely powerful and expressive function; we will come back to it later. 9.8.4 Filtering the Elements of a List Another common list operation is to select some elements from a list and return a sublist. For example, the following function takes a list of strings and returns a list that contains only the strings containing a vowel: sub contains-vowel(Str $string) { return True if $string ~~ /<[aeiouy]>/; } sub filter_words_with_vowels (@strings) { my @kept-string; 154 Chapter 9. Arrays and Lists } for @string -> $st { push @kept-string, $st if contains-vowel $st; } return @kept-string; contains-vowel is a subroutine that returns True if the string contains at least one vowel (we consider y to be a vowel for our purpose). The filter_words_with_vowels subroutine will return a list of strings containing at least one vowel. An operation like filter_words_with_vowels is called a filter because it selects some of the elements and filters out the others. Raku has a function called grep to do that in just one statement: my @filtered = grep { /<[aeiouy]>/ }, @input; The name of the grep built-in function used to filter some input comes from the Unix world, where it is a utility that filters the lines that match a given pattern from an input file. In the code example above, all of @input strings will be tested against the grep block, and those matching the regex will go into the filtered array. Just like map, the grep function iteratively assigns each item of the @input array to the $_ topical variable, applies the code block following the grep keyword to $_, and returns a list of the values for which the code block evaluates to true. Here, the code block is a simple regex applied to the $_ variable. Just as for map, we could have used a function reference as the first argument to grep: my @filtered = grep &contains-vowel, @input; To generate a list of even numbers between 1 and 10, we might use the range operator to generate numbers between 1 and 10 and use grep to filter out odd numbers: my @evens = grep { $_ %% 2 }, 1..10; # -> [2 4 6 8 10] As an exercise, write a program using map to produce an array containing the square of the numbers of the input list and a program using grep to keep only the numbers of an input list that are perfect squares. Solution: A.7.3. Most common list operations can be expressed as a combination of map, grep, and reduce. 9.8.5 Higher Order Functions and Functional Programming Besides their immediate usefulness, the reduce, map and grep functions we have been using here do something qualitatively new. The arguments to these functions are not just data: their first argument is a code block or a function. We are not only passing to them the data that they will have to use or transform, but we are also passing the code that will process the data. The reduce, map, and grep functions are what are often called higher-order functions, functions that manipulate not only data, but also other functions. These functions can 9.9. Fixed-Size, Typed and Shaped Arrays 155 be thought of as generic abstract functions they perform a purely technical operation: process the elements of a list and apply to each of them a behavior defined in the code block or the function of the first parameter. These ideas are to a large extent rooted in functional programming, a programming paradigm that is very different from what we have seen so far and that has been implemented historically in languages such as Lisp, Caml, Ocaml, Scheme, Erlang, or Haskell. Raku is not a functional programming language in the same sense as these languages, because it can also use other programming paradigms, but it has incorporated most of their useful features, so that you can use the expressive power and inherent safety of this programming model, without being forced to do so if and when you would prefer a different model, and without having to learn a totally new syntax that may sometimes look somewhat abstruse or even clunky. This is immensely useful and can give you an incredible expressive power for solving certain types of problems. But other types of problems might be better solved with the more traditional procedural or imperative programming model, while others may benefit from an object-oriented approach. Raku lets you choose the programming model you want to use, and even makes it possible to combine seamlessly several of them in the same program. Functional programming is so important in my opinion that a full chapter of this book will be devoted to the functional programming features of Raku (see Chapter 14). Before that, make sure to read the Subsection A.7.1.5 in the array and list section of the exercise solution chapter. 9.9 Fixed-Size, Typed and Shaped Arrays By default, arrays can contain items of any type, including items of different types, and can auto-extend as you need. Raku will take care of the underlying gory details for you, so that you dont have to worry about them. This is very practical but also comes with a cost: some array operations might be unexpectedly slow, because Raku may have to perform quite a bit of house-cleaning behind the scene, such as memory allocation or reallocation, copying a full array within memory, etc. In some cases, however, it is possible to know beforehand the size of an array and the data type of its items. If Raku knows about these, it might be able to work faster and to use much less memory. It might also helps you to prevent subtle bugs. To declare the type of the elements of an array, just specify it when declaring the array. For example, to declare an array of integers: > my Int @numbers = 1..20; [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20] > @numbers[7] = 3.5; # ERROR Type check failed in assignment to @numbers; expected Int but got Rat in block at line 1 Similarly, you can declare the size of an array. Such arrays are sometimes called shaped arrays. There are twelve months in a year, so you might tell Raku that your @months array will never contain more that twelve items: 156 Chapter 9. Arrays and Lists > my @months[12] = 1..7; [1 2 3 4 5 6 7 (Any) (Any) (Any) (Any) (Any)] > say @months.elems 12 > say @months[3]; 4 > say @months[12]; Index 12 for dimension 1 out of range (must be 0..11) Here, Raku has allocated 12 slots to the array, even though the last five are currently undefined. Raku may not need to reallocate memory when you define the tenth item of the array. And Raku tells you about your mistake if you accidentally try to access an outof-range item. Defining both the type of the elements and the maximal size of the array may lead to a noticeable performance gain in terms of execution speed (at least for some operations) and reduce significantly the memory usage of the program, especially when handling large arrays. 9.10 Multidimensional Arrays The arrays we have seen so far are one-dimensional. In some languages, such arrays are called vectors. But arrays can also be multidimensional (you may then call them matrices). For example, you might use a two-dimensional array to store a list of employees with their respective salaries: > my @employees; [] > @employees[0;0] = "Liz"; Liz > @employees[0;1] = 3000; 3000 > @employees[1] = ["Bob"; 2500]; [Bob 2500] > @employees[2] = ["Jack"; 2000]; [Jack 2000] > @employees[3] = ["Betty"; 1800]; [Betty 1800] > say @employees[1;1]; 2500 > say @employees[2]; [Jack 2000] > say @employees; [[Liz 3000] [Bob 2500] [Jack 2000] [Betty 1800]] It is possible to have more than two dimensions. For example, we could have a tridimensional matrix to store the temperatures in a chemical reactor, measured in various locations identified by their x, y, and z coordinates: 9.11. Sorting Arrays or Lists 157 my @temp; @temp[1;3;4] = 80; For this type of data, however, it is often easier to use the data structure that we will cover in the next chapter, hashes. Multidimensional arrays can also have a fixed size. For example, this may be a declaration for two-dimensional array where the first dimension is the month in the year and the second the day in the month: my @date[12, 31]; 9.11 Sorting Arrays or Lists Sorting data is a very common operation in computer science. Raku has a sort function that can sort an array or a list and return the sorted result: say sort <4 6 2 9 1 5 11>; # -> (1 2 4 5 6 9 11) There are several types of sorts. The most common are numeric sort and lexicographic (or alphabetic) sort. They differ in the way they compare individual items to be sorted. In alphabetic sort, you first compare the first letter of the words to be compared; a word starting with an a will always come before a word starting with a b (or any other letter) in an ascending sort, irrespective of the value or number of the other characters. You need to compare the second character of two words only if the first character of these words is the same. Numeric sorting is very different: it is the overall value of the number that is of interest. For example, if we are sorting integers, 11 is larger than 9 because it has more digits. But alphabetic sorting of 9 and 11 would consider 11 to be smaller than 9, because the first digit is smaller. So an alphabetic or lexicographic sort of the list of integers above would return: (1 11 2 4 5 6 9) The consequence is that, with many programming languages, when you want to sort data, you need to specify which type of sort you want. With consistent data (every item of the same type), Raku is usually clever enough to find out which type of sort is best suited to your needs. So, for example, this code will perform the type of sort that you probably expect: say sort ; # ->(a ab abc ac bc ca cb) Even with mixed data types, sort can do a pretty good job at providing a result that may very well be what you are looking for: say sort <1 b 11 5 cb 4 12 a ab abc 42 ac bc ca >; # -> (1 4 5 11 12 42 a ab abc ac b bc ca cb) 158 Chapter 9. Arrays and Lists There are cases, however, where this simple use of the sort function will fail to return what you probably want: say sort ; # -> (A AC BAC a ab abc bc) Here, sort puts all strings starting with an uppercase letter before any string starting with a lower case letter, probably not what you want. It looks even worse if the strings use extended ASCII characters: say sort ; # -> (A AC BAC a ab abc bc b) The reason is that, when sorting strings, sort uses the internal numeric encoding of letters. This was sometimes called "ASCIIbetical" order (by contrast with alphabetical order), but the term is now too limited and somewhat obsolete, because Raku is using Unicode rather than ASCII. Clearly, these are cases where more advanced sorting techniques are needed. 9.12 More Advanced Sorting Techniques The sort routine typically takes two arguments, a code object and a list of items to be sorted, and returns a new sorted list. If no code object is specified, as in the examples we have seen above, the cmp built-in comparison operator is used to compare the elements. If a code object is provided (and if it accepts two arguments), then it is used to perform the comparison, which tells sort which of the two elements should come first in the final order. There are three built-in comparison operators that can be used for sorting. They are sometimes called three-way comparators because they compare their operands and return a value meaning that the first operand should be considered less than, equal to or more than the second operand for the purpose of determining in which order these operands should be sorted. The leg operator coerces its arguments to strings and performs a lexicographic comparison. The <=> operator coerces its arguments to numbers (Real) and does a numeric comparison. The aforementioned cmp operator is the smart three-way comparator, which compares strings with string semantics and numbers with number semantics. Most of our simple examples above worked well with strings and numbers because they implicitly used the default cmp operator, which guesses quite well which type of comparison to perform. In other words, this: say sort <4 6 2 9 1 5 11>; # -> (1 2 4 5 6 9 11) is equivalent to this: say sort { $^a cmp $^b }, <4 6 2 9 1 5 11>; # -> (1 2 4 5 6 9 11) 9.12. More Advanced Sorting Techniques 159 The code block used here as the first argument to the sort routine uses the placeholder parameters (or self-declared parameters) seen earlier in this chapter. The cmp routine receives two arguments that are bound to $^a and $^b and returns to the sort function information about which of the two items should come first in the resulting order. If you wanted to sort in reverse order, you could just swap the order of the two placeholder parameters: say sort { $^b cmp $^a }, <4 6 2 9 1 5 11>; # -> (11 9 6 5 4 2 1) Note that this example is given only for the purpose of explaining some features of the placeholder parameters. To sort the array weve presented here in descending order, it might just be easier to obtain the same result with the following code: say reverse sort <4 6 2 9 1 5 11>; # -> (11 9 6 5 4 2 1) The reason sort does a good job even with mixed strings and integers is because the default comparison function, cmp, is pretty clever and guesses by looking at its arguments whether it should perform a lexicographic order or numeric order comparison. If sorting gets too complicated for cmp, or, more generally, when a specific or custom order is required, then you have to write your own ad-hoc comparison subroutine. For example, if we take again the example of strings with mixed-case letters, we may achieve a case-insensitive alphabetical order this way: say sort { $^a.lc cmp $^b.lc}, ; # -> (a A ab abc AC BAC bc) or this way: say sort { $^a.lc leg $^b.lc}, ; # -> (a A ab abc AC BAC bc) Here, when the comparison code block receives its two arguments, the lc method casts them to lowercase before performing the comparison. Notice that this has no impact on the case of the output, since the lowercase transformation is local to the comparison code block and has no impact on the data handled by sort. We will see shortly that there is a simpler and more efficient way of doing such a transformation before comparing the arguments. If the comparison specification is more complicated, we may need to write it in a separated subroutine and let sort call that subroutine. Suppose we have a list of strings that are all formed of leading digits followed by a group of letters and possibly followed by other irrelevant characters, and that we want to sort the strings according to the group of letters that follows the digits. Lets start by writing the comparison subroutine: sub my_comp ($str1, $str2) { my $cmp1 = $0 if $str1 ~~ /\d+(\w+)/; my $cmp2 = $0 if $str2 ~~ /\d+(\w+)/; return $cmp1 cmp $cmp2; } 160 Chapter 9. Arrays and Lists Nothing complicated: it takes two arguments, uses a regex for extracting the group of letters in each of the arguments, and returns the result of the cmp function on the extracted strings. In the real world, something might need to be done if either of the extractions fails, but we will assume for our purposes here that this will not happen. The sorting is now quite straight forward, we just need to pass the above subroutine to the sort function: say sort &my_comp, < 22ac 34bd 56aa3 12c; 4abc( 1ca 45bc >; # -> (56aa3 4abc( 22ac 45bc 34bd 12c; 1ca) We only need to prefix the comparison subroutine with the & ampersand sigil and it works fine: the strings are sorted in accordance to the letter groups that follow the leading digits. In all the examples above, the comparison subroutine accepted two parameters, the two items to be compared. The sort function may also work with a code object taking only one parameter. In that case, the code object is not a comparison code block or subroutine, but is a code object implementing the transformation to be applied to the items before using the default cmp comparison routine. For example, if we take once more the example of strings with mixed-case letters, we may achieve a case-insensitive alphabetical order yet in a new way: say sort { $_.lc }, ; # -> (a A ab abc AC BAC bc) This could also be written with a placeholder parameter: say sort { $^a.lc }, ; # -> (a A ab abc AC BAC bc) Here, since the comparison code block takes only one argument, it is meant to transform each of the items to be compared before performing the standard cmp routine on the arguments. This not only makes things simpler, but is also probably more efficient, especially if the number of items to be sorted is large and if the transformation subroutine is relatively costly: the transformed values are actually cached (i.e., stored in memory for repeated use), so that the transformation is done only once for each item, despite the fact that the comparison routine is called many times for each item in a sort. Similarly, we could sort numbers according to their absolute values: say sort {$_.abs}, <4 -2 5 3 -12 42 8 -7>; # -> (-2 3 4 5 -7 8 -12 42) If you think about it, the more complicated example with digits and letters requiring a separate subroutine is also applying the same transformation to both its arguments. As an exercise, write a (simpler) sorting program using a transformation subroutine and the default cmp operator on transformed items. Solution: A.7.4. Needless to say, the (so-called) advanced uses of the sort function presented in this section are yet more examples of the functional programming style. The comparison subroutines and the transformation subroutines are passed around as arguments to the sort function, and, more broadly, all of the functions, subroutines, and code blocks used here are higherorder functions or first-class functions. 9.13. Debugging 9.13 161 Debugging Careless use of arrays (and other mutable objects) can lead to long hours of debugging. Here are some common pitfalls and ways to avoid them: 1. Some array built-in functions and methods modify their argument(s) and others dont. It may be tempting to write code like this: @array = splice @array, 1, 2, $new_item; # WRONG! The splice function returns the elements it has deleted from the array, not the array itself, which is modified in place. Before using array methods and operators, you should read the documentation carefully and perhaps test them in interactive mode. When traversing an array, for example with for or map, the $_ topical variable is an alias for the successive items of the array, and not a copy of them. This means that if you change $_, the change will be reflected in the array. There may be some cases where this is what you want, and others where you dont care (if you no longer need the original array), but this technique is error-prone and should perhaps be avoided (or at least used only with great care). my @numbers = <1 2 3>; push @doubles, $_*=2 for @numbers; say @numbers; # -> [2 4 6] # WRONG (probably) The error here is that the $_*=2 statement is modifying $_, so that the @numbers array is also modified, whereas the intent was certainly to populate the new numbers into @doubles, not to modify @numbers. The same code applied to a literal list instead of an array leads to a run time error because a list is immutable: > push @doubles, $_*=2 for <1 2 3>; # WRONG (definitely) Cannot assign to an immutable value The fix is quite easy in this case and consists of using an expression that does not modify $_ but returns the new desired value: push @doubles, $_ * 2 for @numbers; # OK The same goes for map: my @numbers = <1 2 3>; say map { ++$_}, @numbers; say @numbers; # -> [2 3 4] # WRONG (probably) Here again, using an expression that does not modify $_ but instead returns the new desired value will fix the problem: my @numbers = <1 2 3>; say map { $_ + 1}, @numbers; say @numbers; # -> [1 2 3] # -> (2 3 4) 162 Chapter 9. Arrays and Lists 9.14 Glossary List An immutable sequence of values. Array A variable containing a mutable sequence of values. Element One of the values in a list or an array (or some other sequence), also called items. Nested array An array that is an element of another array. Accumulator A variable used in a loop to add up or accumulate a result. Reduce A processing pattern that traverses a sequence and accumulates the elements into a single result. Map A processing pattern that traverses a sequence and performs an operation on each element. Also the name of a Raku built-in function that performs such a processing pattern. Filter A processing pattern that traverses a list and selects the elements that satisfy some criterion. grep is a Raku implementation of a filter. Alias A circumstance where an identifier refers directly to some variable or value, so that a change to it would lead to a change to the variable or value. It essentially means having two names for the same value, container or object. 9.15 Exercises Exercise 9.1. Write a subroutine called nested-sum that takes an array of arrays of integers and adds up the elements from all of the nested arrays. For example: my @AoA = [[1, 2], [3], [4, 5, 6]]; say nested-sum(@AoA); # -> 21 Solution: A.7.5. Exercise 9.2. Write a subroutine called cumul-sum that takes a list of numbers and returns the cumulative sum, that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. For example: my @nums = [1, 2, 3, 4]; say cumul-sum(@nums); # -> [1, 3, 6, 10] Solution: A.7.6. Exercise 9.3. Write a subroutine called middle that takes a list and returns a new list that contains all but the first and last elements. For example: say middle(1, 2, 3, 4); # -> (2, 3) Solution: A.7.7. Exercise 9.4. Write a subroutine called chop-it that takes an array, modifies it by removing the first and last elements, and returns nothing useful. For example: 9.15. Exercises my @nums = 1, 2, 3, 4; chop-it(@nums); say @nums; 163 # -> [2, 3] Solution: A.7.8. Exercise 9.5. Write a subroutine called is-sorted that takes a list (or array) of numbers as a parameter and returns True if the list is sorted in ascending order and False otherwise. For example: > is-sorted (1, 2, 2); True > is-sorted (1, 2, 1); False Solution: A.7.9. Exercise 9.6. Two words are anagrams if you can rearrange the letters from one to spell the other. Write a subroutine called is-anagram that takes two strings and returns True if they are anagrams. Solution: A.7.10. Exercise 9.7. Write a subroutine called has-duplicates that takes a list or an array and returns True if there is any element that appears more than once. It should not modify the original input. Solution: A.7.11. Exercise 9.8. This exercise pertains to the so-called Birthday Paradox, which you can read about at http: // en. wikipedia. org/ wiki/ Birthday_ paradox . If there are 23 students in your class, what are the chances that two of you have the same birthday? You can estimate this probability by generating random samples of 23 birthdays and checking for duplicates. Hint: you can generate random birthdays with the rand and the int functions. Solution: A.7.12. Exercise 9.9. Write a subroutine that reads the file words.txt and builds a list with one element per word. Write two versions of this function, one using the push method and the other using the idiom unshift. Which one takes longer to run? Why? Solution: A.7.13. Exercise 9.10. To check whether a word is in our standard word list, you could check each element in turn, but it would be slow because it searches through the words in order. If the words are in alphabetical order (which is the case of our word list), we can speed things up considerably with a bisection search (also known as binary search), which is similar to what you do when you look a word up in the dictionary. You start somewhere in the middle and check to see whether the word you are looking for comes before the word in the middle of the list. If so, you search the first half of the list the same way. Otherwise, you search the second half. Either way, you cut the remaining search space in half. If the word list has 113,809 words, it will take at most about 17 steps to find the word or conclude that its not there. Write a function called bisect that takes a sorted list and a target value and returns information about whether the target value is in the list or not. Solution: A.7.14 164 Chapter 9. Arrays and Lists Exercise 9.11. Two words are a reverse pair if each is the reverse of the other. For example, depot and toped form a reverse pair; other examples include reward and drawer, or desserts and stressed. Write a program that finds all the reverse pairs in the word.txt file. Solution: A.7.15. Exercise 9.12. Two words interlock if taking alternating letters from each forms a new word. For example, shoe and cold interlock to form schooled. Write a program that finds in word.txt all pairs of words that interlock. Hint: dont enumerate all pairs, there are many of them! Solution: A.7.16 Credit: this exercise is inspired by an example at http: // puzzlers. org . Chapter 10 Hashes This chapter presents another built-in type called a hash. Hashes are one of Rakus best and most commonly used features; they are the building blocks of many efficient and elegant algorithms. 10.1 A Hash is a Mapping A hash is like an array, but more general. In an array, the indices or subscripts have to be integers; in a hash, they can be (almost) anything. A hash contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. A key and a value together form a pair (an object of the Pair type), or a key-value pair. A hash can be viewed as a collection of key-value pairs. The values in a hash can also be called items or elements, as with arrays. In other programming languages, hashes are sometimes called dictionaries, hash tables, maps, or associative arrays. In mathematical language, a hash represents a mapping from keys to values, so you can also say that each key maps to a value. As an example, well build a hash that maps from English to Spanish words, so the keys and the values are all strings. In Raku, hash names start with the % sigil. To create a new hash, you just declare it this way: > my %eng2sp; This creates an empty hash. To add items to the hash, you can use curly braces (a.k.a. curly brackets and sometimes simply curlies): > %eng2sp{'one'} = 'uno'; uno This line creates an item that maps from the key 'one' to the value 'uno'. If the key is a string containing a single word (i.e., without any space in the middle of it), there is a more idiomatic shortcut to create the same hash entry: 166 Chapter 10. Hashes > %eng2sp = 'uno'; uno If we print the hash, we see a key-value pair with a => pair constructor operator between the key and value: > say %eng2sp; one => uno This output format is also an input format. For example, you can create a new hash with three items: > my %eng2sp = ('one' => 'uno', 'two' => 'dos', 'three' => 'tres'); one => uno, three => tres, two => dos Using the => pair constructor operator between keys and values is not required; you may use a comma as well: my %eng2sp = ('one', 'uno', 'two', 'dos', 'three', 'tres'); But the pair constructor has the advantage of showing more graphically the key-value relations. The pair constructor operator also makes the use of quotes non mandatory on its lefthand side (provided the key is a string with no space): > my %eng2sp = (one => 'uno', two => 'dos', three => 'tres'); one => uno, three => tres, two => dos You might also use a more concise list syntax for the hash assignment and Raku will happily convert the list into a hash, provided the number of items in the input list is even: > my %eng2sp = ; one => uno, three => tres, two => dos You might be surprised by the output. The order of the key-value pairs is usually not the order in which you populated the hash. In general, the order of items in a hash is unpredictable. But thats not a problem because the elements of a hash are never indexed with integer subscripts. Instead, you use the keys to look up the corresponding values: > say %eng2sp ; dos The key two always maps to the value 'dos' so the order of the items doesnt matter. If the key isnt in the hash, you get an undefined value: > say %eng2sp ; (Any) The elems method or function works on hashes just as on arrays; it returns the number of key-value pairs: 10.1. A Hash is a Mapping 167 > say %eng2sp.elems; 3 > say elems %eng2sp 3 The :exists adverb also works on hashes as on arrays; it tells you whether something appears as a key in the hash (appearing as a value is not good enough)1 : > %eng2sp :exists; True > %eng2sp :exists; False To see whether something appears as a value in a hash, you can use the values method, which returns a collection of values, and then use a loop (or possibly a grep) to look for the searched item: my @vals = values %eng2sp; for @vals -> $value { say "Found it!" if $value eq 'uno'; } # -> Found it! Or more concisely: say "Found it!" if grep {$_ eq 'uno'}, %eng2sp.values; Since grep defaults to a smart match, this can be made even more concise: say "Found it!" if grep 'uno', %eng2sp.values; # -> Found it! When looking for values, the program has to search the elements of the list in order (or sequentially), as in Section 7.2.2. As the list gets longer, the search time gets longer in direct proportion. By contrast, when looking for keys, Raku uses a hashing algorithm that has a remarkable property: it takes about the same amount of time no matter how many items are in the hash. In other words, it performs really fast, compared to the list size, when the searched list is large. This is the reason why the solution to the reverse pair exercise (Exercise 9.11) of the previous chapter using a hash was almost three times faster than the bisection search solution (see Subsection A.7.15). As an exercise, use the sample employee data of the multidimensional array of Section 9.10 (p. 156), load it into a hash, and look up some salaries. Hint: you dont need a multidimensional structure for doing that with a hash. Solution: A.8.1 1 Evaluating the value in a Boolean context would also work with our example, but this would return something wrong when the key exists, but the value is not defined or otherwise evaluates to a false value (for example if it is equal to False, zero, or an empty string). 168 Chapter 10. Hashes 10.2 Common Operations on Hashes Weve seen already that to populate a hash, you can just assign an even list to it. The four syntactical forms below are correct: my my my my %first_quarter = ("jan" => 1, "feb" => 2, "mar" => 3); %second_quarter = (apr => 4, may => 5, jun => 6); %third_quarter = jul => 7, aug => 8, sep => 9; %fourth_quarter = < oct 10 nov 11 dec 12 >; To add an element to a hash, just assign the hash with a key: my %months = ("jan" => 1, "feb" => 2, "mar" => 3); %months{'apr'} = 4; say %months; # -> apr => 4, feb => 2, jan => 1, mar => 3 Remember that you can also do the same without having to quote the keys if you use the angle brackets quote-word operator (if the keys are strings): %months = 4; # same as: %months{'apr'} = 4; or you can also use the push function with a pair: > push %months, (may => 5); apr => 4, feb => 2, jan => 1, mar => 3, may => 5 > my $new-pair = jun => 6 jun => 6 > push %months, $new-pair; apr => 4, feb => 2, jan => 1, jun => 6, mar => 3, may => 5 Using push to add a pair to a hash is not exactly the same, though, as making a hash assignment: if the key already exists, the old value is not replaced by the new oneinstead, the old and the new ones are placed into an array (or, if the old value is already an array, then the new value is added to the array): > push %months, (jan => '01'); {apr => 4, feb => 2, jan => [1 01], jun => 6, mar => 3, may => 5} To check whether a value is defined for a given key, use defined: > say True if defined %months ; True To obtain the number of items in a hash, use the elems method: say %months.elems; # -> 6 To remove a hash item, use the :delete adverb: > push %months, (jud => 7); # Oops, a typo! apr => 4, feb => 2, jan => 1, jud => 7, jun => 6, mar => 3, may => 5 > %months{'jud'}:delete; # typo now removed 7 > say %months apr => 4, feb => 2, jan => 1, jun => 6, mar => 3, may => 5 10.3. Hash as a Collection of Counters 169 Note that the :delete adverb also returns the value that is being removed. To iterate over a hash, use: kv to retrieve the interleaved keys and values; keys to retrieve the keys; values to retrieve the values; pairs to retrieve the key-value pairs; For example: > for %months.kv -> $key, $val { say "$key => $val" } jan => 1 apr => 4 mar => 3 jun => 6 may => 5 feb => 2 > say keys %months; (jan apr mar jun may feb) > say values %months; (1 4 3 6 5 2) > say %months.pairs; (jan => 1 apr => 4 mar => 3 jun => 6 may => 5 feb => 2) 10.3 Hash as a Collection of Counters Suppose you are given a string and you want to count how many times each letter appears. There are several ways you could do it: You could create 26 variables, one for each letter of the alphabet. Then you could traverse the string and, for each character, increment the corresponding counter, probably using an ugly and huge 26-part chained conditional. You could create an array with 26 elements. Then you could convert each character to a number (using the built-in function ord), use the number as an index into the array, and increment the appropriate counter. You could create a hash with characters as keys and counters as the corresponding values. The first time you see a character, you would add an item to the hash. After that, you would increment the value of an existing item. Each of these options performs the same computation, but each of them implements that computation in a different way. An implementation is a way of performing a computation; some implementations are better than others. For example, an advantage of the hash implementation is that we dont have to know ahead of time which letters appear in the string and we only have to make room for the letters that do appear. Here is what the code might look like: 170 Chapter 10. Hashes sub histogram (Str $string) { my %histo; for $string.comb -> $letter { %histo{$letter}++; } return %histo; } The name of the function is histogram, which is a statistical term for a collection of counters (or frequencies). The first line of the function creates an empty hash. The for loop traverses the string. Each time through the loop, if the character $letter is not in the hash, Raku creates a new item with key $letter and defaults the values to 0 when the ++ operator is called on it, so that the first value immediately thereafter is 1. If $letter is already in the hash, the value is incremented. Heres how it works: > say histogram("We all live in a yellow submarine") W => 1, a => 3, b => 1, e => 4, i => 3, l => 5, (...) y => 1 The histogram indicates that the letters 'W' and 'b' appear only once; 'a' and 'i' appear three times, 'e' appears four times, and so on. 10.4 Looping and Hashes If you use a hash in a for statement, it traverses the pairs of the hash: > for %eng2sp -> $pair { say $pair} two => dos three => tres one => uno We have named the iteration variable $pair to point out more clearly that the program is iterating over key-value pairs (actually Pair objects). You may use the key and value (notice the singular) methods to access the key and value of a Pair. For example, to reverse the order in which each line is printed: > for %eng2sp -> $pair { say $pair.value ~ " <= " ~ $pair.key; } dos <= two tres <= three uno <= one Again, the keys are in no particular order. To traverse the keys in sorted order, you can use the keys (plural) and sort functions or methods: my %histo = histogram("We all live in a yellow submarine"); for %histo.keys.sort -> $key { say "$key\t%histo{$key}"; } 10.5. Reverse Lookup 10.5 171 Reverse Lookup Given a hash %hash and a key $k, it is easy to find the corresponding value $val = %hash{$k}. This operation is called a lookup and, as already mentioned, this is fast even when the hash is very large. But what if you have $val and you want to find $k? You have three problems: first, there might be more than one key that maps to the value $val; depending on the application, you might be able to pick one, or you might have to make an array that contains all of them. Second, there is no simple syntax to do a reverse lookup; you have to search. Third, it might be time-consuming if the hash is large. Here is a function that takes a value and returns the first key that maps to that value: sub reverse-lookup (%hash, $val) { for %hash -> $pair { return $pair.key if $pair.value eq $val; } return; } This subroutine is yet another example of the search pattern. If we get to the end of the loop, that means $val doesnt appear in the hash as a value, so we return an undefined value (Nil). Here, the responsibility to react to that situation is left to the caller. An alternative might be to raise an exception, which would still have to be dealt with by the caller. However, since direct lookup with the key is not raising an exception but simply returning an undefined value when the key does not exist, it makes sense for reverse-lookup to have the same behavior when the value is not found. Here is an example of a successful reverse lookup: > my %histo = histogram('parrot'); a => 1, o => 1, p => 1, r => 2, t => 1 > my $key = reverse-lookup %histo, "2"; r And an unsuccessful one: > say reverse-lookup %histo, "3"; Nil Another more concise way to do reverse lookup would be to use grep to retrieve a list of values satisfying our condition: say grep { .value == 2 }, %histo.pairs; # -> (r => 2) Another option is to use an expression with the first built-in function to retrieve only the first one: my %histo = histogram('parrot'); say %histo.pairs.first: *.value == 1; # -> p => 1 172 Chapter 10. Hashes This latter example uses the * whatever parameter which we havent covered yet in this book. Lets just say that, here, the * stands successively for every pair of the hash, and the first function returns the first pair that matches the condition on the value (see Section 14.6.3 for details on the * parameter). A reverse lookup is much slower than a forward lookup; if you have to do it often, or if the hash gets big, the performance of your program will suffer. 10.6 Testing for Existence A quite common task is to determine whether something exists or if a given value has already been seen in a program. Using a hash is usually the best solution because finding out whether there is an entry for a given key is very simple and also very efficient: you just need to store the values that you want to watch as a key entry in a hash, and then check for its existence when needed. In such a case, you often dont really care about the value and you might put basically anything. It is quite common in that case to use 1 as a value, but you might as well store True or any other value you like. Suppose we want to generate 10 random integers between 0 and 49, but want to make sure that the integers are unique. We can use the rand method 10 times on the desired range. But the likelihood to hit twice the same number is far from negligible (see Exercise 9.8 on the so-called Birthday Paradox and its solution (Subsection A.7.12) for a similar situation). For example, trying this: > my @list; [] > push @list, 50.rand.Int for 1..10; > say @list; [12 25 47 10 19 20 25 42 33 20] produced a duplicate value in the list (25) on the first try. And the second try produced three pairs of duplicates: > say @list; [45 29 29 27 12 27 20 5 28 45] We can use a hash to reject any generated random integer that has already been seen. The following is a possible way to code this: my @list; my %seen; while @list.elems < 10 { my $random = 50.rand.Int; next if %seen{$random}:exists; %seen{$random} = 1; push @list, $random; } say @list; 10.7. Hash Keys Are Unique 173 Every valid integer generated is added to both the %seen hash and the output list. But before doing that, the generated integer is checked against the %seen hash to verify that it has not been seen yet. When this program is finished running, the list has 10 unique (pseudo-)random integers. We have made it step by step and kept two separate data structures, the @list output array and the %seen hash, to make the process as clear as possible. If you think about it, however, @list and %seen have essentially the same content at any step through the loop. We dont really need to keep track of the same data in two places. Since having a hash is important for checking that the output values are unique, we can get rid of @list and write a more concise and probably more idiomatic version of the same program: my %seen; while %seen.elems < 10 { my $random = 50.rand.Int; push %seen, ($random => 1) unless %seen{$random}:exists; } say keys %seen; # -> (39 12 46 27 14 21 4 38 25 47) This can be further simplified. It is not really necessary here to check whether the generated integer exists in the hash: if it does exist, the old hash element will be replaced by the new one, and the hash will be essentially unchanged. In addition, when evaluated in a scalar numeric context, a hash returns the number of its elements, so that the call to the .elems is not necessary. This is the new version: my %seen; %seen{50.rand.Int} = 1 while %seen < 10; say keys %seen; # -> (46 19 5 36 33 1 20 45 47 30) This last version is probably more concise and more idiomatic, but thats not meant to say that it is better. It is perfectly fine if you prefer the second or the first version, maybe because you find it clearer. Use whichever version you like better, or your own modified version provided it does the expected work. This is Raku, there is more than one way to do it (TIMTOWTDI). Note however that the pure hash version doesnt keep the order in which the numbers were generated, so (pseudo)randomness might not be as good. Also note, by the way, that Raku has a pick function or method to choose elements at random from a list without repetition. 10.7 Hash Keys Are Unique It is not possible to have the same key in a hash more than once. Trying to map a new value to a key will replace the old value with the new one. Here is an example of hash creation with duplicates keys: > my %friends = (Tom => 5, Bill => 6, Liz => 5, Tom => 7, Jack => 3) Bill => 6, Jack => 3, Liz => 5, Tom => 7 174 Chapter 10. Hashes Because two of our friends are named Tom, we lose the data associated with the first of them. This is something you should be careful about: hash keys are unique, so youll lose some items if the data associated with your keys has duplicates. The next section will show some ways of dealing with this possible problem. But this key uniqueness property also has very interesting upsides. For example, a typical way of removing duplicates from a list of items is to assign the list items to the keys of a hash (the value does not matter); at the end of the process, the list of keys has no duplicates: > my [a b > my a => > my [z a @array = < a b c d s a z a r e s d z r a > c d s a z a r e s d z r a] %unique = map { $_ => 1 }, @array; 1, b => 1, c => 1, d => 1, e => 1, r => 1, s => 1, z => 1 @unique_array = keys %unique; e s d c b r] As you can see, duplicates have been removed from the output array. In such a simple case, the unique built-in function would have been sufficient to remove duplicates from @array, but within a more complex program, it is quite common to use a hash (often called %seen) to check whether a value has already been seen. 10.8 Hashes and Arrays Inverting a hash can be very easy if it is known that the values can happen only once (that they are unique). Consider for example a hash mapping months to their number in the year (we limit the example to five months for brevity): > my %months = jan => 1, feb => 2, mar => 3, apr => 4, may => 5; apr => 4, feb => 2, jan => 1, mar => 3, may => 5 We can transform the key-value pairs into a flat list, reverse the list, and assign the reversed list to a new hash: > my %rev_months = %months.kv.reverse; 1 => jan, 2 => feb, 3 => mar, 4 => apr, 5 => may We now have a new hash mapping month numbers to their names. This can be very handy if a hash is known to be bijective, but this approach does not work correctly if a value can happen more than once: in such a case, some pairs will be lost: > my %months = jan feb => 2, february > my %rev_months = 1 => january, 2 => => 1, january => 1, feb => 2, february => 2; => 2, jan => 1, january => 1 %months.kv.reverse; february Arrays can appear as values in a hash. For example, if you are given a hash that maps from letters to frequencies, you might want to invert it; that is, create a hash that maps from frequencies to letters. Since there might be several letters with the same frequency, each value in the inverted hash should probably be an array of letters. Here is a function that inverts such a hash: 10.8. Hashes and Arrays 175 sub invert-hash (%in-hash) { my %out-hash; for %in-hash.kv -> $key, $val { push %out-hash{$val}, $key; } return %out-hash; } Each time through the loop, a hash item is assigned to the $key and $val variables, and $key is appended to the value %output-hash for the $val key; if that value does not exist yet, it is created. At the end of the process, the values of %output-hash are all anonymous arrays. Here is an example: my %rev-hist = invert-hash histogram 'parrot'; say %rev-hist; dd %rev-hist; This will display: 1 => [p a o t], 2 => [r] Hash %rev-hist = {"1" => $["p", "a", "o", "t"], "2" => $["r"]} Notice that the say function gives a simple representation of the hash data, and that the new dd (short for data dumper) function used here gives more detailed information. dd is not very commonly used in normal programs, but can be quite useful while debugging a program to display a detailed description of a complex data structure 2 . %output-hash contains two items (two pairs) whose values are anonymous arrays. You can access the second element of the first array using the hash value %rev-hist{"1"} as if it was any ordinary array name, with this simple syntax: say %rev-hist{"1"}[1]; # -> a Figure 10.1 is a state diagram showing %hist and %rev-hist . A hash is represented as a box with the type hash above it and the key-value pairs inside. Arrays can be values in a hash, as this example shows, but they cannot be keys. If you try, youre likely to end up with a key that contains only one item of the array, but most likely not what you intended: my @a = 'a' .. 'c'; my %h; %h{@a} = 5; say %h; # -> a => 5, b => (Any), c => (Any) Here, Raku interpreted the %h{@a} = 5; assignment as a a slice assignment, i.e., assumed that we were trying to populate three items in one go, one for each element of the array. 2 To tell the full truth, dd is not standard Raku, it is a Rakudo-specific debugging feature. A future implementation of Raku not based on Rakudo might not have it. 176 Chapter 10. Hashes Figure 10.1: State diagram. As mentioned earlier, a hash is implemented using a hashing function and that means that the keys have to be hashable 3 . A hashing is a function that takes a value (of any kind) and returns an integer. Hashes use these integers, called hash values, to store and look up key-value pairs. This system works fine if the keys are immutable. But if the keys are mutable, like with arrays, bad things would happen. For example, when you create a key-value pair, Raku would hash the key and store it in the corresponding location. If you modify the key and then hash it again, it would go to a different location. In that case, you might have two entries for the same key, or you might not be able to find a key. Either way, the hash wouldnt work correctly. Thats why keys have to be hashable, and why mutable types like arrays arent. So Raku will do something else that can be useful (such as creating three distinct hash items in the example above), but will not hash the array itself. Since hashes are mutable, they cant be used as keys, but they can be used as values, so that you can have nested hashes. 10.9 Memos If you played with the fibonacci subroutine from Section 5.8, you might have noticed that the bigger the argument you provide, the longer the subroutine takes to run. Furthermore, the run time increases extremely quickly. To understand why, consider Figure 10.2, which shows the call graph for fibonacci with n=4. A call graph shows a set of subroutine frames, with lines connecting each frame to the frames of the functions it calls. At the top of the graph, fibonacci with $n=4 calls fibonacci with $n=3 and $n=2. In turn, fibonacci with $n=3 calls fibonacci with $n=2 and $n=1. And so on. 3 This is not entirely true. The keys of a normal hash must be hashable and therefore immutable. There is another type of hash, object hashes, for which the need to have immutable keys does not apply. 10.9. Memos 177 Figure 10.2: Call graph. Count how many times fibonacci(0) and fibonacci(1) are called. This is an inefficient solution to the problem, and it gets much worse as the argument gets bigger. One solution is to keep track of values that have already been computed by storing them in a hash. A previously computed value that is stored for later use is called a memo. Here is a memoized version of fibonacci: my %known = 0 => 1, 1 => 1; say fibonacci(10); sub fibonacci ($n) { return %known{$n} if %known{$n}:exists; %known{$n} = fibonacci($n-1) + fibonacci($n-2); return %known{$n}; } %known is a hash that keeps track of the Fibonacci numbers we already know. It starts with two items: 0 and 1, which both map to 1. Whenever fibonacci is called, it checks %known. If the result is already there, it can return immediately. Otherwise, it has to compute the new value, add it to the hash, and return it. If you run this version of fibonacci and compare it with the original, you will find that it is much faster, especially for a large argument (say more than 30). Memoizing is a form of caching, i.e., storing in memory the result of a (presumably costly) computing operation in order to avoid computing it again. This process is sometimes called trading memory against CPU cycles. In some cases, such as our Fibonacci recursive example here, the gain can be absolutely huge: calculating the 100th Fibonacci number would take billions of years with the original recursive subroutine and it takes only a split second with the memoized version. Please note that in the specific case of the Fibonacci function, we are storing values for each successive integer; we could have memoized the Fibonacci numbers in an array rather than in a hash (and it might even be slightly more efficient), but using a hash for such purpose is a more general solution, working even when the memo keys are not consecutive integers. As an exercise, try to rewrite the fibonacci subroutine using an array instead of a hash to memoize the calculated Fibonacci numbers. 178 Chapter 10. Hashes 10.10 Hashes as Dispatch Tables You may need a procedure to launch some action depending on the value of a parameter received by the program. To do that, you could use a series of if {...} elsif {...} else {...} statements like this: sub run-stop { ... }; sub run-start { ... }; my $param = get-param; if $param eq "stop" { run-stop; } elsif $param eq "start" { run-start; } elsif $param = "h" { say $help; } elsif $param = "help" { say $help; } elsif $param = "v" { $verbose = True; } else { die "Unknown option $param"; } This approach is boring and error-prone. Using a dispatch table is often a simpler solution. A dispatch table is a data structure mapping identifiers to code references or subroutine objects. Applied to the above scenario, it could look like this: sub run-stop { ... }; sub run-start { ... }; my %dispatch = ( stop => &run-stop, start => &run-start, h => { say $help; }, help => { say $help; }, v => { $verbose = True;}, ); my $param = get-param(); die "Unknown option $param" unless %dispatch{$param}:exists; %dispatch{$param}(); # execute the action specified in %dispatch The %dispatch hash defines the action depending on the parameter used as a key. The %dispatch{$param}() statement calls the required action. This approach is a bit more concise and slightly cleaner, but there are some other advantages. It is more maintainable: if you need to add one option, you just need to add one entry to the hash and dont have to add code in the middle of a complicated chain of nested if {...} elsif {...} else {...} statements at the risk of breaking up something. Another upside is that the dispatch table can be dynamically modified at run time, for example depending on certain external circumstances (for example the day in the month when the program is running) or in accordance with a configuration file. This means that 10.11. Global Variables 179 it is possible to dynamically modify the behavior of a program after compile time, while it is already running. This paves the way to some very interesting advanced programming techniques that are beyond the scope of this book. Note that we have been using hashes for our dispatch tables, and this is the most common way to implement them. If it makes sense to have small integers as keys, you could also implement a dispatch table as an array. This is the case, for example, with numbered menu items where the user is prompted to type a number to indicate which menu option to activate. 10.11 Global Variables In the memoized Fibonacci example above, the %known hash is created outside the subroutine, so it belongs to the whole main package. Such variables are sometimes called global because they can be accessed from any function. Unlike local lexical variables, which usually disappear when their scope ends, global variables persist from one subroutine call to the next. It is common to use global variables for flags; that is, boolean variables that indicate (flag) whether a condition is true. For example, some programs use a flag named $verbose to control the level of detail in the output: my $verbose = True; sub example1 { say 'Running example1' if $verbose; # ... } Global variables are also sometimes used for environment variables and parameters passed to the program, as well as for storing a large data structure that is the centerpiece of a program, in order to avoid copying it when passing it around as an argument to subroutines. But, asides from those specific cases, it is usually considered poor practice to use a global variable, because it creates dependencies and unexpected action-at-a-distance behaviors between various parts of a program and may lead to difficult-to-track bugs. In the case of our memoized fibonacci subroutine, the %known hash is useful only within the subroutine. We can improve the implementation by using the state declarator within the subroutine: say fibonacci(10); sub fibonacci ($n) { state %known = 0 => 1, 1 => 1; return %known{$n} if %known{$n}:exists; %known{$n} = fibonacci($n-1) + fibonacci($n-2); return %known{$n}; } The state declarator makes the variable local to the subroutine and persistent from one call to the subroutine to another: the code line with the state statement is executed only once (at the first call of the subroutine) and the content of variable, the %known hash in this case, is kept from one call to the next. 180 Chapter 10. Hashes 10.12 Debugging As you work with bigger datasets it can become unwieldy to debug by printing and checking the output by hand. Here are some suggestions for debugging large data sets: Scale down the input If possible, reduce the size of the dataset. For example if the program reads a text file, start with just the first 10 lines, or with the smallest example you can find. You can either edit the files themselves, or (better) modify the program so it reads only the first n lines. If there is an error, you can reduce n to the smallest value that manifests the error, and then increase it gradually as you find and correct errors. Check summaries and types Instead of printing and checking the entire dataset, consider printing summaries of the data: for example, the number of items in a hash or the total of a list of numbers. A common cause of runtime errors is a value that is not the right type. For debugging this kind of error, it is often enough to print the type of a value (think about the .WHAT method). It is often useful to add typing to your variables. Where you expect a string, make sure you type the variable or subroutine parameter with Str. If you expect an integer, type it with Int. If you expect an Int of a certain range, create a subset for it as in Section 5.9 (p. 79) and type the variable with that. Write self-checks: Sometimes you can write code to check for errors automatically. For example, if you are computing the average of a list of numbers, you could check that the result is not greater than the largest element in the list or less than the smallest. This is called a sanity check because it detects results that are insane. Another kind of check compares the results of two different computations to see if they are consistent. This is called a consistency check. Format the output Formatting debugging output can make it easier to spot an error. We saw an example in Section 5.11. The dd function displays helpful details on a composite or complex data structure. Again, time you spend building scaffolding can reduce the time you spend debugging. 10.13 Glossary Mapping A relationship in which each element of one set corresponds to an element of another set. Hash A mapping from keys to their corresponding values. key-value pair: The representation of the mapping from a single key to its value. Item In a hash, another name for a key-value pair. Key An object that appears in a hash as the first part of a key-value pair. Value An object that appears in a hash as the second part of a key-value pair. This is more specific than our previous use of the word value. 10.14. Exercises 181 Implementation A way of performing a computation. Hash table The algorithm used to implement hashes. Hash function A function used by a hash table to compute the location of a key. Hashable A type that has a hash function. Immutable types like numbers and strings are hashable; mutable types like arrays and hashes are not. Lookup A hash operation that takes a key and finds the corresponding value. Reverse lookup A hash operation that takes a value and finds one or more keys that map to it. Call graph A diagram that shows every frame created during the execution of a program, with an arrow from each caller to each callee. Memo A computed value stored to avoid unnecessary future computation. Memoize To store a computed value in memory to avoid having to recompute it. Memoizing is a form of caching. Global variable A variable defined outside any subroutine or other block. Global variables can be accessed from any subroutine. Flag A Boolean variable used to indicate whether a condition is true. 10.14 Exercises Exercise 10.1. Write a subroutine that reads the words in words.txt and stores them as keys in a hash. (It doesnt matter what the values are.) Then you can use the exists adverb as a fast way to check whether a string is in the hash. If you did Exercise 9.10, you can compare the speed of this implementation with a hash and the bisection search. Solution: A.8.2 Exercise 10.2. Memoize the Ackermann function from Exercise 5.2 and see if memoization makes it possible to evaluate the subroutine with bigger arguments. Hint: no. Solution: A.8.3. Exercise 10.3. If you did Exercise 9.7, you already have a function named has-duplicates that takes a list as a parameter and returns True if any object appears more than once in the list. Use a hash to write a faster, simpler version of has-duplicates. Solution: A.8.4. Exercise 10.4. Two words are rotate pairs if you can rotate one of them and get the other (see rotate_word in Exercise 7.3) using the Caesar cipher. Write a program that reads a wordlist (e.g. words.txt and finds all the rotate pairs. Solution: A.8.5. Exercise 10.5. Heres another Puzzler from Car Talk (http: // www. cartalk. com/ content/ puzzlers ): This was sent in by a fellow named Dan OLeary. He came upon a common one-syllable, five-letter word recently that has the following unique property. When you remove the first letter, the remaining letters form a homophone of the original word, that is a word 182 Chapter 10. Hashes that sounds exactly the same. Replace the first letter, that is, put it back and remove the second letter and the result is yet another homophone of the original word. And the question is, whats the word? Now Im going to give you an example that doesnt work. Lets look at the five-letter word, wrack. W-R-A-C-K, you know like to wrack with pain. If I remove the first letter, I am left with a four-letter word, R-A-C-K. As in, Holy cow, did you see the rack on that buck! It must have been a nine-pointer! Its a perfect homophone. If you put the w back, and remove the r, instead, youre left with the word, wack, which is a real word, its just not a homophone of the other two words. But there is, however, at least one word that Dan and we know of, which will yield two homophones if you remove either of the first two letters to make two, new four-letter words. The question is, whats the word? You can use the hash from Exercise 10.1 above to check whether a string is in words.txt. To check whether two words are homophones, you can use the CMU Pronouncing Dictionary. You can download it from http: // www. speech. cs. cmu. edu/ cgi-bin/ cmudict . Write a program that lists all the words in words.txt (or in the CMU dictionary) that solve the Puzzler. Solution: A.8.6. Chapter 11 Case Study: Data Structure Selection At this point you have learned about Rakus core data structures, and you have seen some of the algorithms that use them. This chapter presents a case study with exercises that let you think about choosing data structures and practice using them. But first, I would like to briefly introduce two conditional structures that have been left aside so far and provide a couple of new possibilities about subroutine signatures. 11.1 The Ternary Conditional Operator Consider the following code that tests the value of a positive integer: my $result; if $num < 10 { $result = "One digit"; } else { $result = "More than one digit"; } say $result; This is quite simple, but a bit long. This can be rewritten in just one line of code: say $num < 10 ?? "One digit" !! "More than one digit"; The operator is in two parts: the ?? and the !!, which separate three expressions (hence the name ternary operator): The condition to be evaluated (is $num less than 10?); The expression defining the value if the condition is true; 184 Chapter 11. Case Study: Data Structure Selection The expression defining the value if the condition is false. This statement checks if $num is less than 10 and, if true, prints "One digit; if the condition is false, it prints More than one digit. This operator does not provide any new functionality; it just offers a more concise syntax. It is possible to nest several ternary operators to examine successively multiple choices: say $value < 10 $value < 100 $value < 1000 ?? "One digit" !! ?? "Two digits" !! ?? "Three digits" !! "More than three digits"; This construct is a form of what is sometimes called a switch statement, because the C language and many languages derived from it use the switch keyword to describe such a multiple choice conditional. This is much more concise and often more convenient than nested if ... then ... else conditionals, but the next section provides a more powerful switch type of statement. 11.2 The given ... when Switch Statement Raku has a switch statement, written with the given and when keywords. The given keyword introduces the variable or expression that will be tested, and each of the when statements specify a condition followed by a block that will execute if the condition is true. By default, the process stops at the first condition that is satisfied. The example just above can be rewritten as follows: given $value { when 0..9 when $_ < 99 when /^\d**3$/ default } { { { { say say say say "One digit" } "Two digits" } "Three digits" } "More than three digits" } The given $value statement topicalizes the argument, i.e., assigns the content of $value to the $_ topical variable (or, more precisely, aliases it to $_). The argument to given is a simple variable in the example above, but it can be a complex expression whose evaluation is stored (and cached) into $_. Each of the when conditions is checked against $_. I have written these conditions in three different syntactical forms to illustrate some of the various possibilities: The first one checks $_ (implicitly) against the 0..9 range. The second one compares explicitly $_ to 99. The third one uses a regex to check whether $_ has three digits. The default statement runs only if the other conditions have failed. 11.3. Multiple Conditionals with Junctions 185 Only one message will be printed, because the matching process stops as soon as one condition has been satisfied, and the default clause will run if no other condition has been met. If there is no specific operator in the when clause, then it will smart match the expression in the when clause against $_: when $foo { ... } # equivalent to: when $foo ~~ $_ { ... } Note that the given keyword is not doing much more than topicalizing its argument for the rest of the block. The when clauses are doing the bulk of the real work. In fact, you could even use the when clauses without a given, provided you assign the right value to $_, which, as you hopefully remember, can be done with a for block: my $val = 7; for $val { when 0..6 { say "less than"} when 7 {say "Exact";} when 8..* {say "greater than";} } It is possible to add a proceed clause at the end of any of the conditional code blocks to prevent the process from stopping after that code block has succeeded. For example, you might write this: given $value { when 0..9 when 10..99 when 42 when /^\d**3$/ default } { { { { { say say say say say "One digit"} "Two digits"; proceed} "The response to the ultimate question"} "Three digits" } "More than three digits" } Here, if $value is 42, two messages will be displayed, Two digits and The response to the ultimate question, because the proceed clause in the second code block prevents the process from stopping on the first successful match. Good, it seems, but there is a problem. The proceed clause should be used with some care, as it can easily lead to unexpected results. In fact, the code above is actually wrong: if $value has two digits but is not 42 (if it is, say, 43), the default block will also run, because the only other successful match had this proceed clause, and will say that there are More than three digits although this is obviously false. As an exercise, test the above code with various values and try to find a way to fix the bug with the proceed clause. Solution: A.9.1 11.3 Multiple Conditionals with Junctions Sometimes, you need to test several possible conditions and would write something like this: 186 Chapter 11. Case Study: Data Structure Selection if $value == 3 or $value == 5 or $value == 7 { #... This is quite verbose, and I dont like to have to repeat the $value == part several times. I would prefer to be able to write something like: If value is 3 or 5 or 7. That syntax doesnt work, but junctions enable you to do almost that: if $value == 3|5|7 { say "$value is either 3, or 5, or 7" } The 3|5|7 part is a junction. Junctions are superpositions of unordered values. Operations on junctions are executed for each item of the junction separately (and maybe even in parallel), and the results are assembled in a junction of the same type. The junction types differ when evaluated in boolean context. The types and associated junction constructors are any, all, one and none. Type Constructor any all one none any all one none Infix Operator | & ^ True if... at least one value evaluates to True no value evaluates to False False exactly one value evaluates to True True no value evaluates to True For example, 3|5|7 is the same as any(3, 5, 7). This is another example of an any junction: my Junction $weekday = any if $day eq $weekday { say "This is a weekday"; } In this example the eq operator is called with each pair $day, Monday, $day, Tuesday, etc. and the result is put into an any-junction again. As soon as the result is determined (in this case, as soon as one comparison returns True), it can abort the execution of the other comparisons. This works not only for operators, but also for routines: if 2 == sqrt(4 | 9 | 16) { say "YaY"; } Junctions can be very handy to perform fairly common tasks. Imagine you have an array of numbers, and you want to check that all of them are non-negative. In most programming languages, you would write a loop to iterate over the array and check each item in turn. In Raku, this is very simple: my @values = get-values(); if all(@values) >= 0 { ... } 11.4. Subroutine Named and Optional Parameters 187 Or, if you want to avoid a division by zero exception: my @values = get-values(); perform-division(@values) if none(@values) == 0; 11.4 Subroutine Named and Optional Parameters The subroutines that we have seen so far used positional parameters, i.e., parameters whose binding with the subroutine call arguments rely on their order within the list of arguments and in the signature. This is usually fine when the number of arguments passed to the subroutine is small (say, three or less). When the subroutine signature becomes longer, using positional arguments might become cumbersome and error-prone. 11.4.1 Named Parameters Named arguments may be supplied in any order: the name of the parameter is bound to the argument having the same name. For example: sub divide (:$dividend, :$divisor where $divisor != 0) { return $dividend/$divisor; } say divide(dividend => 2048, divisor => 128); # -> 16 # or: say divide(divisor => 128, dividend => 2048); # -> 16 The arguments are supplied at the subroutine call as a list of pairs using the pairconstructor syntax. In the signature, the parameters are retrieved with the so-called colonpair syntax: the $dividend parameter is bound to the value of the pair whose key is dividend (2048), and $divisor is similarly bound to 128, irrespective of the order of the arguments in the subroutine call. These named parameters are especially useful when the number of arguments is large. For example, we havent covered object-oriented programming yet (see Chapter 12), but this is how we could create an object of the (user-defined) Rectangle class: my $rect = Rectangle.new( origin_x => 100, origin_y => 200, width => 23, length => 42, color => 'black' ); Clearly, using five positional parameters would be unpractical. 188 Chapter 11. Case Study: Data Structure Selection 11.4.2 Optional Parameters Sometimes, the actual number of arguments is not known in advance: for example, a subroutine may be called with a variable number of arguments. Such a subroutine is said to be variadic. You can define a parameter to be optional by postfixing it with a question mark in the subroutine signature: sub my-sub($x, $y?) { # simple optional parameter if $y.defined { say "The second parameter has been supplied and defined"; } else { say "The second parameter has not been supplied"; } # ... } When using positional parameters, the optional parameters always have to be the last ones in the list (after the mandatory ones). A parameter can also be made optional by supplying a default value: sub my-log($number, $base = e) { # e is a predefined constant # $base is an optional parameter return log($number) / log($base); } say my-log(4); # Natural log (base e) say my-log(32, 2); # Log base 2 say my-log(100, 10); # Common log (base 10) -> 1.38629436111989 -> 5 -> 2 Here, if the second argument is not supplied, the default value (e) is used instead. Conversely, if there is a second argument, it overrides the default value. Sometimes, having optional or default parameters is not good enough. For example, the subroutine may have to process a list containing any number of values. For situations like this, you can use a slurpy parameter, i.e., a kind of array placed at the end of the parameter list that will slurp up all the remaining arguments. This kind of slurpy parameter uses the *@ twigil. In the following example, the subroutine takes one mandatory parameter (the first number of the list) and a list of additional arguments that will be stored in the @rest array: sub my-sum($first-num, *@rest) { say @rest; return $first-num + [+] @rest; } say my-sum 1, 3, 4, 5, 12, 17; # -> [3 4 5 12 17] # -> 42 Some further examples of slurpy parameters have been provided in Section A.7.1. 11.5 Word Frequency Analysis Now, lets get to the case study. As usual, you should at least attempt the exercises before you read the suggested solutions, which are provided in the following sections of this chapter. 11.6. Random Numbers 189 Exercise 11.1. Write a program that reads a file, breaks each line into words, strips whitespace and punctuation from the words, and converts them to lowercase. Exercise 11.2. Go to Project Gutenberg (http: // gutenberg. org ) and download your favorite out-of-copyright book in plain text format. Modify your program from the previous exercise to read the book you downloaded, skip over the header information at the beginning of the file, and process the rest of the words as before. Then modify the program to count the total number of words in the book, and the number of times each word is used. Print the number of different words used in the book. Compare different books by different authors, written in different eras. Which author uses the most extensive vocabulary? Exercise 11.3. Modify the program from the previous exercise to print the 20 most frequently used words in a given book. Exercise 11.4. Modify the previous program to read a word list (see Section 8.2) and then print all the words in the book that are not in the word list. How many of them are typos? How many of them are common words that should be in the word list, and how many of them are really obscure? 11.6 Random Numbers Given the same inputs, most computer programs generate the same outputs every time, so they are said to be deterministic. Determinism is usually a good thing, since we expect the same calculation to yield the same result. For some applications, though, we want the computer to be unpredictable. Games are an obvious example, but there are more. Making a program truly nondeterministic turns out to be difficult, but there are ways to make it at least seem nondeterministic. One of them is to use algorithms that generate pseudorandom numbers. Pseudorandom numbers are not truly random because they are generated by a deterministic computation, but just by looking at the numbers it is all but impossible to distinguish them from random. Raku provides functions such as rand that generate pseudorandom numbers (which we will simply call random numbers from here on). The function rand returns a random number (of Num type) between 0.0 and 1.0 (including 0.0 but not 1.0). Each time you call rand, you get the next number in a long series. To see a sample, run this loop in the REPL: say rand for 1..5; Used as a method, rand returns a random number between 0.0 and the value of the invocant. For example, 10.rand returns a random number between 0 and 10 (10 not included). You might try it as a one-liner: $ raku -e 'say 10.rand for 1..5' 8.23987158729588 9.83276889381497 2.52313276833335 3.44713459548771 1.82329894347025 190 Chapter 11. Case Study: Data Structure Selection You should hopefully get a different output than I did. If you want to run such a one-liner under Windows, remember that youll need to replace single quotes with double quotes. To obtain random integers between 1 and 10, you may use the Int and rand methods: $ raku -e 'say 10.rand.Int + 1 for 1..5' 5 10 1 6 3 The pick function or method takes a number $count and a list as arguments and returns $count items chosen at random and without repetition. For example: > say <1 3 4 5 7 9 10 12 14 42>.pick(5); (5 42 3 4 7) > say pick 5, <1 3 4 5 7 9 10 12 14 42>; (42 12 5 1 9) If $count if greater than or equal to the number of items of the list, then all elements from the list are returned in a random sequence. To obtain random unique integers in a range, you might use pick on a range: > say pick 5, 1..20; (5 3 6 18 7) > say (1..20).pick(5); (20 4 18 2 7) If you dont specify the number of random numbers, youll get one random pick: > say (1..20).pick; 19 Exercise 11.5. Write a function named choose_from_hist that takes a histogram as defined in Section 10.3 and returns a random value from the histogram, chosen with probability in proportion to frequency. For example, for the three items: ('a', 'a', 'b'), your function should return 'a' with probability 2/3 and 'b' with probability 1/3. 11.7 Word Histogram You should attempt the previous exercises before you go on. For the purpose of presenting the solutions to the above exercises, Ive used the plain text of Emma (1816), the novel by Jane Austen, downloaded from the Gutenberg project (http: //www.gutenberg.org/files/158/158-0.txt) and saved in a file called emma.txt 1 Use the same text if you want to compare your solutions and results with mine. Here is a program that reads the emma.txt file and builds a histogram of the words in the file: 1 The Gutenberg project slightly modified the format of this file after this chapter was written. To avoid any problem associated with this change (and any other future changes), you can download the original file from my Github repository: https://github.com/LaurentRosenfeld/think_raku/blob/master/Supplementary/ emma.txt. 11.7. Word Histogram 191 my %histogram; my $skip = True; # flag to skip the header sub process-line(Str $line is copy) { if defined index $line, "*END*THE SMALL PRINT!" { $skip = False ; return; } return if $skip; $line ~~ s:g/<[-']>/ /; # Replacing dashes and apostrophes with spaces $line ~~ s:g/<[;:,!?.()"_`]>//; # removing punctuation symbols $line = $line.lc; # setting string to lower case for $line.words -> $word { %histogram{$word}++; } $skip = True if $line ~~ /^finis$/; } process-line $_ for "emma.txt".IO.lines; The program reads each line of the emma.txt file and, for each line, calls process-line. The process-line subroutine skips the header lines (i.e., all the lines until a line containing the string *END*THE SMALL PRINT! is met 2 ). It replaces dashes and apostrophes with spaces, removes various punctuation characters, and sets the line to lower case. Finally, it splits the line into individual words that are stored and counted with an accumulator in the %histogram hash. To know whether the program is doing something like what it is supposed to do, we can display a few entries of the %histogram hash: # displaying 20 lines of the histogram my $count; for %histogram -> $pair { say sprintf "%-24s %d", $pair.key, $pair.value; $count++; last if $count > 20; } This prints out the following output: embarrassing hows appealed bestow articulate demands closely dull 1 1 2 2 1 2 1 9 2 This line is no longer present in the new version of the Emma file currently on the Gutenberg project site. So this will work only with my version of this file on my Github repository: https://github.com/ LaurentRosenfeld/think_raku/blob/master/Supplementary/emma.txt. 192 Chapter 11. Case Study: Data Structure Selection hearts column possesses attributed jumped forwards wittier expert attractive asserted oftentimes fancy finds 1 1 1 1 2 2 2 2 2 2 1 38 1 To count the total number of words in the file, we can add up the values in the histogram: my $word_count = [+] %histogram.values; say "There are $word_count words in the book."; The number of different words is just the number of items in the hash: my $distinct-words = %histogram.elems; say "There are $distinct-words distinct words in the book."; Note that you could reduce the above to one code line by interpolating a code block within the output string: say "There are {%histogram.elems} distinct words in the book." And the results: There are 161991 words in the book. There are 7110 distinct words in the book. 11.8 Most Common Words To find the most common words in emma.txt, we can sort the %histogram hash according to the values (word frequencies) and retrieve the 10 most frequent words into an array. my @most_commons = (sort { %histogram{$^b} cmp %histogram{$^a} }, %histogram.keys)[0..9]; say $_ for map { "$_ \t%histogram{$_} "}, @most_commons; The sort functions receives the keys of the histogram and its comparison function compares the values associated with those keys. Since we use the key $^b before the key $^a, the sort will produce a reverse (descending) sort order. The whole sort procedure is placed within parentheses, so that the subscript range [0..9] acts as a slice on the list produced by sort and retains only the first 10 most frequent words. The result is stored into the @most_commons array. The next code line just reprocesses the array to display the words and their respective frequency. This displays the following output: 11.9. Optional Parameters to the and of i a it her was she 193 5241 5205 4897 4295 3192 3130 2529 2490 2400 2364 If you want to see more interesting words, you might, as a further exercise, filter the histogram and retain only words that have more than, say, four letters. The @most_commons temporary array is not really needed. We could do the whole thing in a single statement: say $_ for map { "$_ \t%histogram{$_} "}, (sort { %histogram{$^b} cmp %histogram{$^a} }, %histogram.keys)[0..9]; This is an example of data pipeline (or stream) programming. Such a statement needs to be read from bottom to top and from right to left. The first step is %histogram.keys, which produces a list of the histogram keys; this list is fed into the sort statement to produce a list of the keys sorted (in descending order) according to their values; once this whole part between parentheses is completed, the subscript range [0..9] retains the 10 most frequent words and feeds them into the map statement, which produces the list of words and frequencies for the final output. Let me add one word of caution here: sorting the histogram by values and picking up the top 10 to get the most frequent words is probably the easiest way to solve the problem and the shortest code to do it. Thats the reason I have used this solution here. But it is not the most efficient solution from the standpoint of the run time, because it involves the cost of sorting a relatively large data set, whereas we are using only a small part of the sorted data. There are some better algorithms to do that from the standpoint of runtime efficiency, but they are more complicated. So, there is a tradeoff here between coding efficiency and performance. Assuming this is code that we want to run only once, I have chosen to favor coding efficiency. 11.9 Optional Parameters We saw earlier in this chapter that subroutines can take optional parameters. We can use this functionality to write a subroutine that prints the most common words in the %histogram hash extracted from emma.txt. display-most-common(%histogram, 5); sub display-most-common (%hist, Int $num = 10) { say $_ for map { "$_ \t%hist{$_} "}, (sort { %hist{$^b} cmp %hist{$^a} }, %hist.keys)[0..$num - 1]; } 194 Chapter 11. Case Study: Data Structure Selection This will display the five top words of the list above (Section 11.8). If we call it without the second parameter: display-most-common(%histogram); we will get the 10 most common words (same list as the one shown in Section 11.8 above), because the default value for the second parameter is 10. 11.10 Hash Subtraction Finding the words from emma.txt that are not in the word list words.txt is a problem you might recognize as set subtraction; that is, we want to find all the words from one set (the words in emma.txt) that are not in the other (the words in words.txt). subtract takes hashes %main and %dict and returns a new hash that contains all the keys from %main that are not in %dict. Since we dont really care about the values, we set them all to 1: sub subtract (%main, %dict) { my %difference; for %main.keys -> $word { %difference{$word} = 1 unless %dict{$word}:exists; } return %difference; } To find the words in emma.txt that are not in words.txt, we need to load the word list into a hash and to call subtract, passing the two hashes as arguments. We also add some code to print the first 20 words not found in the word list: my %word-list = map { $_ => 1 }, "words.txt".IO.lines; my %unknown-words = subtract(%histogram, %word-list); say %unknown-words.keys.head(20); Notice that rather than using a subscript slice, I have used here the head method to print out the first 20 words of the list. This is just another way to get the first n items of a list or array. There is also a tail method to retrieve the last n items of a list or an array. Here are some of the results from Emma: (penetrated unsullied bateses outstepped particularity experienced italian sunday solicitously blockhead unbleached ult 26th christian 7th untouched iii greensward houseroom tete) Some of these words are names and ordinal numbers. Others are rare or no longer in common use. But a few are common words that should really be in the list! Note that I have used a hash (%unknown-words) here to store the words of emma.txt not found in the word list. Since we are using the data only to print a sample of 20 words, we could have used an array as well. 11.11. Constructing New Operators 11.11 195 Constructing New Operators Learning about hash subtraction is an excellent opportunity to introduce a very interesting functionality of Raku: the capacity to construct new operators or to redefine existing ones. Since we are subtracting two lists of words, it is tempting to use the minus sign to denote this subtraction operation. It is very easy to create such an operator in Raku: multi sub infix:<-> (%main, %dict) { my %difference; for %main.keys -> $word { %difference{$word} = 1 unless %dict{$word}:exists; } return %difference; } Compared to the definition of the subtract subroutine, the only differences are in the header line. We will cover the details in a later chapter, but let us briefly explain here. Most Raku operators are defined as multi subroutines, i.e., subroutines that can be defined several times with different signatures and bodies; Raku will know which one to use depending on the signature. Here we define the minus operator as a multi subroutine whose parameters are two hashes; this will be enough for the Raku compiler to know that we dont want the regular subtraction between numerical values, but something else that applies to two hashes. The minus operator is defined as infix, which means that the operator will be placed between its two operands. Calling this new operator is now just as easy as calling the regular subtraction operator between numbers; we just need to use two hashes as operands: my %unknown-words = %histogram - %word-list; The rest of the program works just as before. This ease or creating new operators is one of the facilities offered by Raku to extend the language from within itself. Well come back to that and other ways to extend the language in later chapters. As an exercise, write a multi subroutine that creates the new postfix ! operator for computing the factorial of an integer: say 5!; # -> 120 Also try to think about how you would test this new ! operator against various input values. Solution: A.9.2 11.12 Sets, Bags and Mixes Raku has a variety of data structure types called Set, Bag and Mix that provide many common set operations. They are unordered collections of unique and weighed items. They are immutable (but there also exist mutable versions of these data structures, SetHash, BagHash and MixHash). You may create and use a set as follows: 196 Chapter 11. Case Study: Data Structure Selection > my $s = set ; set(banana, orange, apple, pear) > say $s.perl set("banana","orange","apple","pear") > say $s.elems; 4 > say $s{'apple'} True > say $s{'strawberry'} False As you can see, duplicates have been removed. Sets only tell us whether or not at least one item of a given name has been seen. A bag, by contrast, also keeps track of how many of each items have been seen: > my $b = bag ; bag(banana(2), orange(3), pear, apple(2)) > say $b{'banana'} 2 Mixes are similar to bags, except that the elements weights dont have to be integers. The interesting thing about these collections is that they can use many set operators commonly used in mathematics, such as the set membership operator (or use (elem) instead if you dont know how to type in your editor 3 ), the or (&) set intersection operator, or the or (<) subset operator: > say "Found it!" if 'apple' $s; Found it! > say "Is subset!" if $s; Is subset! > say $s; set(banana, orange) Notice that we havent used the set keyword to define the list in the second example above. This list has been coerced to a Set to check whether it was a subset of the $s set. This is one of the great things about these collections: most of these set operators can be used with lists, arrays, and hashes. We can rewrite the hash subtraction program using a set for the word list and the (or (elem)) set membership operator: my %histogram; my $skip = True; # flag to skip the header sub process-line(Str $line is copy) { # (same as above) } process-line $_ for "emma.txt".IO.lines; 3I cant teach you here how to type these characters, because each editor will require a different method. 11.13. Random Words 197 my $word-list = set "words.txt".IO.lines; my %unknown-words = subtract(%histogram, $word-list); say %unknown-words.keys.head(20); sub subtract (%main, $dict) { my %difference; for %main.keys -> $word { %difference{$word} = 1 unless $word $dict; } return %difference; } The code line in the for loop could also be written as follows: %difference{$word} = 1 unless $word (elem) $dict; #or: %difference{$word} = 1 if $word / $dict; #or: %difference{$word} = 1 if $word !(elem) $dict; #or even with the (cont) or 3 contain operator: %difference{$word} = 1 unless $dict (cont) $word; #or: %difference{$word} = 1 unless $dict 3 $word; #or: %difference{$word} = 1 if $dict 63 $word; # etc. The \ 4 and (-) built-in operators provide a set difference, so that we needed neither to write a subtract subroutine nor to construct our own minus operator: process-line $_ for "emma.txt".IO.lines; my $word-list = set "words.txt".IO.lines; my $unknown-words = %histogram.keys (-) $word-list; say $unknown-words.keys.head(20); There are more than 30 set operators available, covering most of the set operators used in mathematics. Ive only shown some that are the most likely to be useful. Check into the official documentation (https://doc.raku.org/language/setbagmix) if you need some others. As an exercise, you may rewrite the process-line subroutine or replace it to use a set or a bag instead of a hash to store the words of emma.txt (and possibly adapt the rest of the program where needed), in order to find the words of the emma.txt that are not in the words.txt. Solution: A.9.3 11.13 Random Words To choose random words from the histogram, the simplest algorithm is to build a list with multiple copies of each word, according to the observed frequency, and then choose from the list with the pick function: my @array = map {| (.key xx .value)}, %histogram; say pick 30, @array; 4 Note that this is unicode character 2216, not the same as the \ backslash 198 Chapter 11. Case Study: Data Structure Selection The expression map {| (.key xx .value)} reads each pair of the histogram and creates a list with .value copies of the string in key. The pick function selects 30 random words from the array. This algorithm works, but it is not very efficient; each time you choose one or some random words, it rebuilds the list, which is as big as the original book. An obvious improvement is to build the list once and then make multiple selections, but the list is still big. An alternative is: 1. Use keys to get a list of the words in emma.txt. 2. Build a list that contains the cumulative sum of the word frequencies (see Exercise 9.2). The last item in this list is the total number of words in the book, n. 3. Choose a random number from 1 to n. Use a bisection search (see Exercise 9.10) to find the index where the random number would be inserted in the cumulative sum. 4. Use the index to find the corresponding word in the newly created word list. Exercise 11.6. Write a program that uses this algorithm to choose a random word from emma.txt. Solution: A.9.4 Note that Raku offers a shortcut to perform the task at hand: when used on a bag, pick returns a random selection of elements, weighted by the values corresponding to each key. Ideally, we should have used a bag instead of a hash to store our %histo histogram, but we did not know about bags at the time. We can, however, construct a bag from the %histo histogram. Consider the following example: > my %histo = ( banana => 5, pear => 1, orange => 12); {banana => 5, orange => 12, pear => 1} > my $fruit-bag = bag map { $_ xx %histo{$_}}, %histo.keys; bag(banana(5), orange(12), pear) > for 1..10 { say $fruit-bag.pick: 5} (banana orange orange orange orange) (orange orange banana orange banana) (orange orange banana orange orange) (pear orange banana banana orange) (orange banana orange orange orange) ... As you can see, the most common item, orange, has been picked more often than the others, and the least common, pear, has not been picked up at all before the fourth draw. As an exercise, you may want to adapt this code to choose random words from emma.txt. 11.14 Markov Analysis If you choose words from emma.txt at random, you can get a sense of the vocabulary, but you probably wont get a sentence: this the small regard harriet which knightley's it most things 11.14. Markov Analysis 199 A series of random words seldom makes sense because there is no relationship between successive words. For example, in a real sentence you would expect an article like the to be followed by an adjective or a noun, and probably not a verb or adverb. One way to measure these kinds of relationships is Markov analysis, which characterizes, for a given sequence of words, the probability of the words that might come next. For example, the second chapter of The Little Prince (1943), the famous novella written by French writer and pioneer aviator Antoine de Saint-Exupry, begins: The first night, then, I went to sleep on the sand, a thousand miles from any human habitation. I was more isolated than a shipwrecked sailor on a raft in the middle of the ocean. Thus you can imagine my amazement, at sunrise, when I was awakened by an odd little voice. It said: "If you please draw me a sheep!" "What!" "Draw me a sheep!" I jumped to my feet, completely thunderstruck. I blinked my eyes hard. I looked carefully all around me. And I saw a most extraordinary small person, who stood there examining me with great seriousness. (...) Now I stared at this sudden apparition with my eyes fairly starting out of my head in astonishment. Remember, I had crashed in the desert a thousand miles from any inhabited region. And yet my little man seemed neither to be straying uncertainly among the sands, nor to be fainting from fatigue or hunger or thirst or fear. Nothing about him gave any suggestion of a child lost in the middle of the desert, a thousand miles from any human habitation. When at last I was able to speak, I said to him: "But what are you doing here?" And in answer he repeated, very slowly, as if he were speaking of a matter of great consequence: "If you please draw me a sheep..." When a mystery is too overpowering, one dare not disobey. Absurd as it might seem to me, a thousand miles from any human habitation and in danger of death, I took out of my pocket a sheet of paper and my fountain-pen. But then I remembered how my studies had been concentrated on geography, history, arithmetic, and grammar, and I told the little chap (a little crossly, too) that I did not know how to draw. He answered me: "That doesnt matter. Draw me a sheep..." But I had never drawn a sheep. So I drew for him one of the two pictures I had drawn so often. It was that of the boa constrictor from the outside. And I was astounded to hear the little fellow greet it with, "No, no, no! I do not want an elephant inside a boa constrictor. A boa constrictor is a very dangerous creature, and an elephant is very cumbersome. Where I live, everything is very small. What I need is a sheep. Draw me a sheep." In this text, the word draw is always followed by the word me, and the phrase draw me is always followed by a sheep. And the phrase a thousand is always followed by miles, but the phrase a thousand miles may be followed by from any human habitation" or by from any inhabited region. 200 Chapter 11. Case Study: Data Structure Selection The result of Markov analysis is a mapping from each prefix (like draw me and a thousand miles) to all possible suffixes (like a sheep and from any habitation or from any inhabited region). Given this mapping, you can generate a random text by starting with any prefix and choosing at random from the possible suffixes. Next, you can combine the end of the prefix and the new suffix to form the next prefix, and repeat. For example, if you start with the prefix draw me, then the next word has to be a sheep, because the prefix is always followed by a sheep in the text. If a prefix is a thousand miles, the next suffix might be from any habitation or from any inhabited region. In this example the lengths of the prefixes are two or three words, but you can do Markov analysis with any prefix length. Exercise 11.7. Markov analysis: 1. Write a program to read a text from a file and perform Markov analysis. The result should be a hash that maps from prefixes to a collection of possible suffixes. The collection might be an array, a hash, a set, a bag, etc.; it is up to you to make an appropriate choice. You can test your program with prefix length two, but it would be nice to write the program in a way that makes it easy to try other lengths. 2. Add a function to the previous program to generate random text based on the Markov analysis. Here is an example from Emma with prefix length 2: it was a black mornings work for her. the friends from whom she could not have come to hartfield any more! dear affectionate creature! you banished to abbey mill farm. now i am afraid you are a great deal happier if she had no hesitation in approving. dear harriet, i give myself joy of so sorrowful an event; For this example, the punctuation has been left attached to the words. The result is almost syntactically correct, but not quite. Semantically, it almost makes sense, but not quite. What happens if you increase the prefix length? Does the random text make more sense? 3. Once your program is working, you might want to try a mash-up: if you combine text from two or more books, the random text you generate will blend the vocabulary and phrases from the sources in interesting ways. Credit: this case study is based on an example from Kernighan and Pike, The Practice of Programming, Addison-Wesley, 1999. You should attempt this exercise before you go on. Then you can study our solution in SubsectionA.9.5. 11.15 Data Structures Using Markov analysis to generate random text is fun, but there is also a point to this exercise: data structure selection. In your solution to the previous exercises, you had to choose: How to represent the prefixes. How to represent the collection of possible suffixes. 11.16. Building Your Own Data Structures 201 How to represent the mapping from each prefix to the collection of possible suffixes. The last one is easy: a hash is the obvious choice for a mapping from keys to corresponding values. For the prefixes, the most obvious options are a string or a list of strings. For the suffixes, one option is a list; another is a histogram (hash). How should you choose? The first step is to think about the operations you will need to implement for each data structure. For the prefixes, we need to be able to remove words from the beginning and add words to the end. For example, if the current prefix is draw me, and the next word is a, you need to be able to form the next prefix, me a in order to find the next suffix, sheep. Your first choice might be an array, since it is easy to add and remove elements, but we also need to be able to use the prefixes as keys in a hash, so that sort of rules out arrays. For the collection of suffixes, the operations we need to perform include adding a new suffix (or increasing the frequency of an existing one), and choosing a random suffix. Adding a new suffix is equally easy for the list implementation or the hash. Choosing a random element from a list is easy; choosing from a hash is harder to do efficiently (see Exercise 11.6). So far we have been talking mostly about ease of implementation, but there are other factors to consider in choosing data structures. One is run time. Sometimes there is a theoretical reason to expect one data structure to be faster than other; for example, we mentioned that a lookup operation is faster for hashes than for arrays, especially when the number of elements is large. But often you dont know ahead of time which implementation will be faster. One option is to implement both of them and see which is better. This approach is called benchmarking. A practical alternative is to choose the data structure that is easiest to implement, and then see if it is fast enough for the intended application. If so, there is no need to go on. If not, there are tools, like profile modules, that can identify the places in a program that take the most time. The other factor to consider is storage space. For example, using a histogram for the collection of suffixes might take less space because you only have to store each word once, no matter how many times it appears in the text. In some cases, saving space can also make your program run faster, and in the extreme, your program might not run at all if you run out of memory. But for many applications, space is a secondary consideration after run time. One final thought: in this discussion, we have implied that we should use one data structure for both analysis and generation. But since these are separate phases, it would also be possible to use one structure for analysis and then convert to another structure for generation. This would be a net win if the time saved during generation exceeded the time spent in conversion. 11.16 Building Your Own Data Structures Raku has a number of compound types such as arrays and hashes that you can combine to construct arrays of arrays, arrays of hashes, hashes of arrays, hashes of hashes, arrays of 202 Chapter 11. Case Study: Data Structure Selection arrays of arrays or hashes, and so on, and this is usually sufficient for most needs. Sometimes, however, you need something very specific that is not built in. Over the years, computer science has studied and used scores of specific data structures such as linked lists, stacks, queues, circular lists, trees of numerous kinds, etc. We will briefly study a couple of them. 11.16.1 Linked Lists A linked list is a collection of items in which each item holds a value (or several values) and a link to the next item of the collection. In many programming languages, arrays have a fixed size (contrary to Raku in which arrays can usually grow according to your needs). In those programming languages, a linked list is often used to represent a variable-size collection of items. We saw in Section 9.4 how to use arrays to build stacks and queues. It was fairly easy. In some lower-level programming languages, you would need linked lists for that. In Raku, a linked list item may be represented by a pair (an object of type Pair). The following code is a very simple example showing how we could implement a stack using a linked list in Raku: sub add-to-stack (Pair $stack-top, $item) { my $new-pair = $item => $stack-top; return $new-pair; } sub take-from-stack (Pair $stack-top) { my $new-top = $stack-top.value; return $stack-top.key, $new-top; } sub create-stack ($item) { return $item => Nil; } my $stack = create-stack (0); for 1..5 -> $item { $stack = add-to-stack($stack, $item); } say "The stack is: ", $stack.perl; for 1..5 { my $value; ($value, $stack) = take-from-stack($stack); say "$value -- ", $stack; } Once populated, the resulting stack looks like this: 5 => 4 => 3 => 2 => 1 => 0 => Nil 11.16. Building Your Own Data Structures 203 This is just given as an example for the construction of a linked list. There is usually no need to use anything like this in Raku, since it is much easier to implement a stack using an array, as seen in Section 9.4, although the same principle can be used for building more advanced data structures. You might still want, as an exercise, to implement a queue (see Section 9.4) using a linked list. 11.16.2 Trees A tree is usually a collection of items in which each item (or node) holds a value (or possibly several values) and two or several links to other items of the collection, the children. Think of a family tree or a tree of directories on a hard disk drive to get the general idea. The ultimate nodes that dont have their own children are often called the leaves. There is usually only one ultimate grandparent node, sometimes called the root (if there is more than one ultimate grandparent, then it is not really a tree but several trees or a forest). Dozens of different types of trees have been invented and their descriptions have filled entire books about computer science algorithms. Some are designed to keep the data sorted, others to maintain balance between the tree branches, and so on. The data structure is often not very complicated, but the algorithms needed to maintain the required properties sometimes can be a bit hairy. For example, a typical tree might hold one value and two links, one to the left child and one to the right child. You might implement such a binary tree in a similar way as the linked list described above, except that the value would no longer be a link to the next element, but an array of two elements, the links to the two children. Or you could follow more closely the linked list model above and have nested pairs. For example, a binary tree might look like this: my $tree = 1 => (( 2 => 3 ) => (4 => (5 => ((6 => 7) => 8)))); The implementation is left as an exercise to the reader. Quite often, though, a tree may be implemented in Raku as a simpler data structure such as a nested array or hash. The next section examines such an example. 11.16.3 Binary Heaps A binary heap is a binary tree that keeps a partial order: each node has a value larger that its parent and less than either of its two children; there is no specific order imposed between siblings. (You could also do it the other way around: you could design heaps in which any node has a value less than its parent.) Because there is no order between siblings, it is not possible to find a particular element without potentially searching the whole heap. Therefore, a heap is not very good if you need random access to specific nodes. But if youre interested in always finding the smallest item, then a heap is a very efficient data structure. Heaps are used for solving a number of CS problems, and serve as the basis for an efficient and very popular sorting technique called heap sort. 204 Chapter 11. Case Study: Data Structure Selection Figure 11.1: The heap corresponding to an array containing the digits 0 to 8 For a human, it is useful to represent a heap in a tree-like form. But a computer can store a heap as a simple array (not even a nested array). For this, the index of an element is used to compute the index of its parent or its two children. The children of an element are the two locations where the indices are about double its index; conversely, the parent of a node is located at about half its index. If the heap starts at index 0, the exact formulas for a node with index $n are commonly as follows: parent: int( ($n-1)/2 ) left child: 2*$n + 1 right child: 2*$n + 2 The root node is at index 0. Its children are at positions 1 and 2. The children of 1 are 3 and 4 and the children of 2 are 5 and 6. The children of 3 are 7 and 8, and so on. Thus, if interpreted as a binary heap, the array: [0, 1, 2, 3, 4, 5, 6, 7, 8] is associated with the tree displayed in Figure 11.1. Here is one way to build a heap (in partial alphabetic order) from a list of unordered letters: sub build-heap (@array, $index is copy) { my $index-val = @array[$index]; while ($index) { my $parent = Int( ($index - 1) / 2); my $parent-val = @array[$parent]; last if $parent-val lt $index-val; @array[$index] = $parent-val; $index = $parent; 11.16. Building Your Own Data Structures } 205 } @array[$index] = $index-val; sub heapify (@array) { for @array.keys -> $i { build-heap @array, $i; } } my @input = ; heapify @input; say @input; Note that the heap is built in place (there is no need for a second array). The resulting array is displayed as follows: [a b g d c k j l f h e m n q p t r o i u s v] Is this a correct heap? Its difficult to say at first glance and checking it manually is somewhat tedious. When writing a program for building such a data structure, it is often useful to write some subroutines to display the content in a way that makes it easier to understand the result and check its correctness. The following code shows two examples of such possible subroutines: sub print-heap (@array) { my $start = 0; my $end = 0; my $last = @array.end; my $step = 1; loop { say @array[$start..$end]; last if $end == $last; $start += $step; $step *= 2; $end += $step; $end = $last if $end > $last; } } sub print-heap2 (@array) { my $step = 0; for @array.keys -> $current { my $left_child = @array[2 * $current + 1]; say "$current\tNode = @array[$current];\tNo child" and next unless defined $left_child; my $right_child = @array[2 * $current + 2] // "' '"; say "$current\tNode = @array[$current];\tChildren: " . " $left_child and $right_child"; 206 Chapter 11. Case Study: Data Structure Selection Figure 11.2: The heap corresponding to the array of letters } } $step++; The first one displays the related tree level by level: (a) (b g) (d c k j) (l f h e m n q p) (t r o i u s v) which makes it easy to draw the tree (see Figure 11.2). The second one shows the children for each node and makes it possible to easily check that the partial alphabetic order constraint is satisfied (i.e., each node is smaller than its children): 0 1 2 3 4 5 6 7 8 9 10 11 Node Node Node Node Node Node Node Node Node Node Node Node = = = = = = = = = = = = a; b; g; d; c; k; j; l; f; h; e; m; Children: Children: Children: Children: Children: Children: Children: Children: Children: Children: Children: No child b d k l h m q t o u v and and and and and and and and and and and g c j f e n p r i s ' ' 11.17. Debugging 12 (...) 21 11.17 207 Node = n; No child Node = v; No child Debugging When you are debugging a program, and especially if you are working on a hard bug, here are some things to try: Reading Examine your code, read it back to yourself, and check that it says what you meant to say. Running Experiment by making changes and running different versions. Often if you display the right thing at the right place in the program, the problem becomes obvious, but sometimes you have to build scaffolding. Running under a debugger A debugger is a utility program that enables you to run a program step by step, so you can follow the execution path and check the content of important variables at crucial points in the program execution, to set break points, etc. Raku provides a debugger, called raku-debug, that makes all these things possible. With the advent of modern high-level languages, many people balk at using a debugger. This is a mistake. A debugger will not help solve every kind of problem, but it can be immensely useful. See Section 12.14 for more information on the Raku debugger. Ruminating Take some time to think! What kind of error is it: syntax, runtime, or semantic? What information can you get from the error messages, or from the output of the program? What kind of error could cause the problem youre seeing? What did you change last, before the problem appeared? Rubber ducking If you explain the problem to someone else, you sometimes find the answer before you finish asking the question. Often you dont need the other person; you could just talk to a rubber duck. Thats the origin of the well-known strategy called rubber duck debugging. I am not making this up; see https: //en.wikipedia.org/wiki/Rubber_duck_debugging. Retreating At some point, the best thing to do is back off, undoing recent changes, until you get back to a program that works and that you understand. Then you can start rebuilding. Beginning programmers sometimes get stuck on one of these activities and forget the others. Each activity comes with its own failure mode. For example, reading your code might help if the problem is a typographical error, but not if the problem is a conceptual misunderstanding. If you dont understand what your program does, you can read it 100 times and never see the error, because the error is in your head. Running experiments can help, especially if you run small, simple tests. But if you run experiments without thinking or reading your code, you might fall into a pattern we call random walk programming, which is the process of making random changes until the program does the right thing. Needless to say, random walk programming can take a very long time. 208 Chapter 11. Case Study: Data Structure Selection You have to take time to think. Debugging is like an experimental science. You should have at least one hypothesis about what the problem is. If there are two or more possibilities, try to think of a test that would eliminate one of them. But even the best debugging techniques will fail if there are too many errors, or if the code you are trying to fix is too big and complicated. Sometimes the best option is to retreat, simplifying the program until you get to something that works and that you understand. Beginning programmers are often reluctant to retreat because they cant stand to delete a line of code (even if its wrong). If it makes you feel better, copy your program into another file before you start stripping it down. Then you can copy the pieces back one at a time. Finding a hard bug requires reading, running (with or without a debugger), ruminating, and sometimes retreating. If you get stuck on one of these activities, try the others. 11.18 Glossary Deterministic Pertaining to a program that does the same thing each time it runs, given the same inputs. Pseudorandom Pertaining to a sequence of numbers that appears to be random, but is generated by a deterministic program. Default value The value given to an optional parameter if no argument is provided. Override To replace a default value with an argument. Benchmarking The process of choosing between various data structures and algorithms by implementing alternatives and testing them (especially their run durations) on a sample of the possible inputs. Debugger A program that lets you run your code line by line and check its state at any step during its execution. Rubber duck debugging Debugging by explaining your problem to an inanimate object such as a rubber duck. Articulating the problem can help you solve it, even if the rubber duck doesnt know Raku. 11.19 Exercises: Huffman Coding Huffman coding is a technique used for data compression, i.e., to reduce the size of a piece of data (such as, for example, compressing a file). 11.19.1 Variable-Length Codes If you are familiar with Morse code, you know that it is a system for encoding the letters of the alphabet as a series of dots and dashes. For example, the famous signal ...-... represents the letters SOS, which comprise an internationally recognized call for help. The table in Figure 11.3 shows the rest of the codes. 11.19. Exercises: Huffman Coding 209 Figure 11.3: International Morse code (public domain) Morse code (invented between 1836 and 1844) was one of the very first attempts at digital encoding of the alphabet of a plain text. The only known earlier attempt is the braille alphabet (1824-1837). Notice that some codes are longer than others. By design, the most common letters have the shortest codes. Since there are a limited number of short codes, that means that less common letters and symbols have longer codes. A typical message will have more short codes than long ones, which minimizes the average transmission time per letter. Codes like this are called variable-length codes. In this exercise, we will look at an algorithm for generating a variable-length code called a Huffman code. It is an interesting algorithm in its own right, but it also makes a useful exercise because its implementation uses a variety of data structures. Here is an outline of what we will do until the end of this chapter: 1. First, we will use a sample of English text to generate a table of characters and their frequencies. 2. Then we will use this frequency table to generate a code table. 3. Finally, we will encode a message with this code table and then decode it. 11.19.2 The Frequency Table Since the goal is to give short codes to common letters, we have to know how often each letter occurs. In Edgar Allan Poes short story The Gold Bug, one of the characters, William Legrand, uses letter frequencies to crack a cypher. He explains: 210 Chapter 11. Case Study: Data Structure Selection Now, in English, the letter which most frequently occurs is e. Afterwards, the succession runs thus: a o i d h n r s t u y c f g l m w b k p q x z. E however predominates so remarkably that an individual sentence of any length is rarely seen, in which it is not the prevailing character. So our first mission is to see whether Poe got it right. To check, lets use as a sample the text of The Gold Bug itself, which can be downloaded from Project Gutenberg (http: //www.gutenberg.org/files/2147/2147-0.txt) and a variety of other websites. Exercise 11.8. Write a program that counts the number of times each letter appears in a sample text. Download the text of The Gold Bug and analyze the frequency of the letters. Solution: see Section A.9.6.1 11.19.3 Building the Huffman Code For our purposes, Morse code has one defect: it does not use just two symbols as you might think, but actually three: in addition to the dots and dashes, it it also implicitly using the space between two symbols, as well as a longer space between two letters. The reason why some space is needed is quite simple. Refer to the Morse code table above and suppose you receive three dots (...). This could be interpreted as the letter e three times , or as ie or ei, or as s, or as the beginning of h, v, 3, 4, or 5. Added spaces make it possible to disambiguate between those various possibilities. But they also make code transmission much slower. In 1951, David A. Huffman invented a code-building technique avoiding this problem: provided that you know where a given letter starts, it is totally unambiguous. For example, we will meet later a Huffman code for a small subset of the alphabet that looks like this: a e s n t d r => => => => => => => .. .-.-.. --. ---. ---- If you start reading a sequence of dots and dashes representing a valid text composed with these seven letters, you can always decode it without any ambiguity. If the first symbol is a dot, then the letter is either an a or a e depending on the next symbol. If the first symbol is a dash and the next one a dot, then the letter must be either a s or an n depending on the third symbol. If the two first symbols are dashes, you can similarly determine that the current letter is a t (if the third symbol is a dot), or a d or a r, which you can find out by looking at the fourth symbol. In brief, you dont need spaces between the symbols, it is always possible to unambiguously decode a letter. How can we build such a Huffman code? Lets do it by hand with a very simple alphabet: the four letters of the nucleo-bases of DNA: A, C, T, and G. Suppose we want to encode the following input string: CCTATCCTCGACTCCAGTCCA 11.19. Exercises: Huffman Coding 211 This gives the following frequency table: C T A G : : : : 10 5 4 2 47.62 23.81 19.05 9.52 To build the Huffman code, we start with the two less frequent letters and merge them into one new temporary symbol, [GA], which we pretend is a new composite letter with a frequency of 6. At this point, we decide that, between two letters, the less frequent one will have an appended dot and the other an appended dash (this is an arbitrary choice, it could be done the other way around). So we say that the symbol for the least common of the two letters (G) will be [GA]. and the symbol for A will be [GA]-. We are now left with three letters, C, T, and [GA]. We merge the two least frequent letters, T and [GA], and can now tell that the symbol for T will be [TGA]. and the symbol for [GA] will be [TGA]-. There are only two letters left, C and TGA, with C the least frequent one; so C will be a dot and TGA a dash. We can now unroll our dummy letters: T is [TGA]., so, replacing [TGA] with its symbol, i.e., a dash, the final code for T will be -.; similarly, [GA]. now translates into --. By the same substitution process, we can now determine that A is --- and G --.. So our final Huffman code table is: C T G A => => => => . -. --. --- Notice that, by construction, the most frequent letter (C) has the shortest code and the least common letters (G and A) the longest codes. Manually encoding the CCTATCCTCGACTCCAGTCCA input string with this code yields the following pseudo-Morse code: ..-.----...-..--.---.-...-----.-...--Note that our Huffman code is not ambiguous: the first dot can only be a C, and the second one also. The next symbol is a dash, which can be the beginning of the three other letters, but only T can have a dot afterwards. The next sequence of symbols is four dashes; this can only be the three dashes of a A, with the last dash being the beginning of the next letter; and -. can only be a T, and so on. In a real-life Huffman encoding for text file compression, we would not use dots and dashes, but 0 and 1 bits; however, dots and dashes are just another nice way of representing those binary values. So, lets just pretend that dots and dashes are really 0 and 1 binary numbers. Did we really achieve data compression? Our pseudo-Morse string has 38 binary symbols. The original input string had 21 characters or bytes, that is 168 bits. The data has been compressed by a factor of about 4.4. Is Huffman coding better than a fixed-length code? A string representation where each letter would be represented by two bits (two bits can represent four letters) would require 212 Chapter 11. Case Study: Data Structure Selection 42 symbols. So, yes, we did obtain a better data compression than a fixed-length encoding (by about 10%). This may seem to be a small achievement, but this is actually quite good with such a small alphabet. With real text data, Huffman coding can achieve significant data compression. Exercise 11.9. 1. Write a program that performs Huffman encoding of a simple string of characters. You may start with the DNA example above. Dont worry, though, if you dont get the same Huffman table as the one above: there can be more than one Huffman code for a given input string; but check that you obtain an unambiguous code. 2. Try it with strings having a larger alphabet (youll probably want to start with a relatively small alphabet, because it can otherwise be tedious to check the result by hand). 3. Write a subroutine to encode an input string into pseudo-Morse using the generated Huffman table. 4. Write a subroutine to decode the pseudo-Morse output youve just generated for the previous question. Solution: see Section A.9.6.2. Part II Moving Forward 215 Now that you have reached the end of the first part of this book, you should non longer be a pure beginner. By now, you should be able to go through the official Raku documentation (https://docs.Raku.org) and find your way. There are many more things to say about programming. The next three chapters will be devoted to more advanced concepts and new programming paradigms, including: Object-oriented programming We will describe how we can construct our own types and methods, which is a way to extend the language. Using grammars This is a form of declarative programming in which you define axioms and rules and derive knowledge from these; grammars are a very powerful way to analyze textual content and are used to transform program source code into executable statements. Functional programming This is yet another programming paradigm in which computation is expressed as the evaluation of mathematical functions. Each of these chapters probably deserves a full book in its own right (and might have one some day), but we hope to tell you enough about them to get you going. In my opinion, every programmer should know about these powerful concepts in order to be able to select the best way to solve a given problem. Raku is a multiparadigm language, so we can really cover these topics in terms of the Raku language. A number of subjects that we have introduced in previous chapters should lead you easily into these new ideas, and this is the reason why I think it is possible to properly cover them with just one chapter for each of these subjects. There will be far fewer exercises in the second part, because we expect you by now to be able to think up your own exercises and make your own experiments for yourself. And there will be only very few suggested solutions, because we are getting at a level where there is really not one right solution, but many possible ways to tackle a problem. Concerning the Raku programming language, we have covered a lot of material, but, as I warned from the very beginning, this is far from exhaustive. The following are among the topics that we have not covered (and will not cover); you might want to explore the documentation on them yourself: Concurrent programming Todays computers have multiple processors or multicore processors; Raku offers various ways of taking advantage of these to run computing processes in parallel in order to improve performance and reduce run time; see https://docs.Raku.org/language/concurrency for more details. Exception handling Managing situations where something goes wrong is an important part of programming. Raku offers various mechanisms to handle such situations. See https://docs.Raku.org/language/exceptions for more details. Interprocess communication: Programs often have to run other programs and to communicate with them. See https://docs.Raku.org/language/ipc. Modules How to create, use, and distribute Raku modules. See https://docs.Raku.org/ language/modules. Native calling interface How to call libraries that are written in other programming languages and follow the C calling conventions. See https://docs.Raku.org/ language/nativecall 216 Chapter 12 Classes and Objects At this point you know how to use functions to organize code and built-in types to organize data. The next step is to learn object-oriented programming, which uses programmerdefined types to organize both code and data. When software applications start to grow large, the number of details to be handled becomes overwhelming. The only way to manage this complexity is to use abstraction and encapsulation. Object orientation is a very popular and efficient way to implement abstraction and encapsulation. Raku is an object-oriented programming language, which means that it provides features that support object-oriented programming, which has these defining characteristics: Programs include class and method definitions. Most of the computation is expressed in terms of operations on objects. Objects often represent things in the real world, and methods often correspond to the ways things in the real world interact. Object-oriented programming in Raku is a big topic that may be worth a book by itself (and there will probably be a book or two on the subject at some point). This chapter will hopefully do more than just skim the surface and enable you to create and use objects, but will not cover some of the details and more advanced features. 12.1 Objects, Methods and Object-Oriented Programming Let us start with a high-level nontechnical overview of object-oriented programming in general and a brief introduction to the jargon associated with it. In computer science, an object may loosely describe a memory location or an entity having a value, and often be referred to by an identifier. This can be a variable, a data structure, an array, or possibly even a function. This general meaning is not the sense that we will use in this chapter. In object-oriented programming (OOP), the word object has a much more specific meaning: an object is an entity which often has: 218 Chapter 12. Classes and Objects An identity (for example its name). Some properties defining its behavior (in the form of special functions that are usually called methods); this behavior usually does not change over time and is generally common to all objects of the same type. A state defined by some special variables (called, depending on the language, attributes, instance data, fields, or members); the state may change over time and is generally specific to each object. In Raku, we speak about attributes. In brief, an object is a set of attributes and methods packed together. Objects are usually defined in a kind of code package called a class. A class defines the methods and the nature of the attributes associated with an object. In Raku, a class makes it possible to define new types similar to the built-in types that we have seen before. Very soon, we will start to define some classes and to use them to create objects. You already know informally what a method is, as we have used built-in methods throughout the book. It is a sort of function with a special postfix syntax using the dot notation on the invocant. For example, you may invoke the say method on a simple string: "foo".say; # -> foo Note that foo isnt an object, but a simple string, but you can invoke the say method on it, because Raku can treat it internally as an object when needed. In some OOP languages, this implicit conversion of a native type into an object is sometimes called autoboxing. You probably also remember that methods can be chained in a process where the value returned by a method becomes the invocant for the next method: "foo".uc.say; # -> FOO my @alphabet = ; @alphabet.sort.uc.say; # prints: ALPHA BRAVO CHARLIE DELTA ECHO FOXTROT GOLF In OOP, methods applicable to objects are usually defined within classes, often the class that also defined the object or some other class closely related to it. In Raku, methods can also be defined in a role, which is another type of code package somewhat resembling to a class, as we will see later. The basic idea of object-oriented programming is that an object is a kind of black box that hides its internals (data and code) from the user; the user can consult or change the state of an object through the methods. Hiding the internals of objects is called encapsulation. This often enables a higher-level view and a better data abstraction than what we have seen so far; this in turns helps to make programs less buggy (especially large programs). In addition, OOP usually also offers the following concepts: polymorphism, i.e., the possibility for a function or a method to do different things depending of the type of object which calls it; inheritance, i.e., the possibility to derive a class from another class, so that the child class inherits some of the properties of the parent class, which is a powerful tool for code reuse. We will now study how all these concepts are implemented in Raku. 12.2. Programmer-Defined Types 12.2 219 Programmer-Defined Types We have used many of Rakus built-in types; now we are going to define a new type. As an example, we will create a type called Point2D that represents a point in two-dimensional space. In mathematical notation, points are often written in parentheses with a comma separating the coordinates. For example, in Cartesian or rectangular coordinates, (0, 0) represents the origin, and ( x, y) represents the point x units to the right and y units up from the origin. x is called the abscissa of the point, and y the ordinate. There are several ways we might represent points in Raku: We could store the coordinates separately in two variables, $x and $y. We could store the coordinates as elements in a list, an array, or a pair. We could create a new type to represent points as objects. Creating a new type is a bit more complicated than the other options, but it has advantages that will be apparent soon. A programmer-defined type is usually created by a class (or a role, but we will come back to that later). A barebones class definition for a point type looks like this: class Point2D { has $.abscissa; has $.ordinate; } # "x" value # "y" value The header indicates that the new class is called Point2D. The body is defining two attributes, i.e., named properties associated with the class, here the abscissa and ordinate (or x and y coordinates) of the point. Defining a class named Point2D creates a type object. The type object is like a factory for creating objects. To create a point, you call the new method on the Point2D class: my $point = Point2D.new( abscissa => 3, ordinate => 4 ); say $point.WHAT; say $point.isa(Point2D); say $point.abscissa; # -> (Point2D) # -> True # -> 3 You can of course create as many points as you wish. The new method is called a constructor and has not been defined in this example; this is not needed because Raku supplies a default new constructor method for every class (well see later how). The method invocation syntax, with the dot notation, is the same as what we have used throughout the book to invoke built-in methods. You are not forced to use this constructor; you can also create your own (and you may name it new or something else), but we will stay with the built-in new method for the time being. 220 Chapter 12. Classes and Objects Figure 12.1: Object diagram. Creating a new object with a class is called instantiation, and the object is an instance of the class. Every object is an instance of some class, so the terms object and instance are interchangeable. But we will often use instance to indicate that we are talking about an object belonging to a programmer-defined type. 12.3 Attributes The attributes that we have defined are properties associated with the Point2D class, but they are specific to the instance of the class that has been created. They are instance attributes. If we create another Point2D object, it will also have these attributes, but the values of these attributes are likely to be different. Figure 12.1 shows the result of these assignments. A state diagram that shows an object and its attributes is called an object diagram. The variable $point refers to a Point2D object, which contains two attributes. Each attribute of the Point2D class should refer to a number, but this is not obvious in the current definition of the class. As it stands right now, we could create a Point2D object with a string for the abscissa, which would not make much sense. We can improve the class definition by specifying a numeric type for the attributes: class Point2D { has Numeric $.abscissa; has Numeric $.ordinate; } # "x" value # "y" value The instance attributes are private to the class, which means that they normally cannot be accessed from outside the class: you would usually need to invoke a method of the class (i.e., a kind of subroutine defined within the class), to get their value. However, when an attribute is defined with a dot as in $.abscissa: has $.abscissa; Raku automatically creates an implicit accessor method, i.e., a method having the same name as the attribute that returns the value of this attribute. Thus, when we wrote: say $point.abscissa; # -> 3 12.3. Attributes 221 we were not accessing directly the abscissa attribute of the $point object, but we were really calling the abscissa method on the object, which in turn returned the value of that attribute. You can use such an accessor with dot notation as part of any expression. For example: my $dist-to-center = sqrt($point.abscissa ** 2 + $point.ordinate ** 2); There is another way to declare an attribute in a class, with an exclamation mark twigil instead of a dot: has $!abscissa; In that case, Raku does not create an implicit accessor method and the attribute can only be accessed from methods within the class. Such an attribute is now fully private. However, if you declare attributes this way, you will not be able to populate them at object creation with the default new constructor and will need to create your own constructor (or indirectly modify new). So dont try that for the time being, as you would not be able to do much with your objects at this point. Well get back to that later. By default, object attributes are not mutable; they are read-only. This means you cannot modify them once the object has been created. This is fine for some attributes: if an object represents a person, that persons name and birth date are unlikely to change. Some other attributes may need to be updated, sometimes very frequently. In such cases, attributes can be declared to be mutable with the is rw trait: class Point2D { has Numeric $.abscissa is rw; has Numeric $.ordinate is rw; } # "x" value # "y" value It is now possible to modify these attributes. For example, we can change the newly created points abscissa: # First creating a Point2D object: my $point = Point2D.new(abscissa => 3, ordinate => 4); say $point; # -> Point2D.new(abscissa => 3, ordinate => 4) # Now moving the $point object two units to the right: $point.abscissa = 5; say $point; # -> Point2D.new(abscissa => 5, ordinate => 4) Almost all of the information presented so far about attributes has been related to instance attributes, i.e., to properties related to individual objects. You can also have attributes pertaining to the whole class, which are named class attributes. They are less common than instance attributes and are declared with the my declarator (instead of has). A typical example of a class attribute would be a counter at the class level to keep track of the number of objects that have been instantiated. 222 Chapter 12. Classes and Objects 12.4 Creating Methods The simple Point2D class and its instance $point are not very useful so far. Lets complete the class definition with some methods: class Point2D { has Numeric $.abscissa; has Numeric $.ordinate; method coordinates { # accessor to both x and y return (self.abscissa, self.ordinate) } } method distance2center { (self.abscissa ** 2 + self.ordinate ** 2) ** 0.5 } method polar-coordinates { my $radius = self.distance2center; my $theta = atan2 self.ordinate, self.abscissa; return $radius, $theta; } We declare three methods in the class: coordinates, a simple accessor to the Cartesian coordinates; distance2center, a method to compute and return the distance between the object and the origin; polar-coordinates, a method to compute the radius and azimuth ($theta) of the object in the polar coordinates system (notice that polar-coordinates invokes the distance2center method to find the radius component of the polar coordinates). A method definition is not very different from a subroutine definition, except that it uses the method keyword instead of the sub keyword. This is not a surprise since a method is essentially a subroutine that is defined within a class (or a role) and knows about its invocant, i.e., the object that called it and its class. And, of course, it has a different calling syntax. Another important difference between a subroutine and a method is that, since there may be several methods with the same name defined in different classes (or different roles), a method invocation involves a dispatch phase, in which the object system selects which method to call, usually based on the class or type of the invocant. However, in Raku, that difference is blurred by the fact that you can have multi subroutines, i.e., subroutines with the same name and a different signature that are also resolved at run time, depending on the arity (number of arguments) and type of the arguments. Within a method definition, self refers to the invocant, the object that invoked the method. There is a short hand for it, $., so that we could write the coordinates method as follows: 12.4. Creating Methods 223 method coordinates { # accessor to both x and y return ($.abscissa, $.ordinate) } The two syntax formats, $. and self, are essentially equivalent. There is a third syntactic way of doing it, using an exclamation mark instead of a dot: method coordinates { # accessor to both x and y return ($!abscissa, $!ordinate) } Here, the result would be the same, but this new syntax is not equivalent: $.abscissa is a method invocation, whereas $!abscissa provides direct access to the attribute. The difference is that $!abscissa is available only within the class (and might be slightly faster), while the method invocation syntax can be used somewhere else (for example in another class). We will see in the next section examples of this distinction and its consequences. We can now create an object and call our methods on it: my $point = Point2D.new( abscissa => 4, ordinate => 3 ); say $point.coordinates; say $point.distance2center; say $point.polar-coordinates; # -> (4 3) # -> 5 # -> (5 0.643501108793284) You might remember from previous chapters that if you use a method without naming an explicit invocant, then the method applies to the $_ topical variable: .say for ; # -> one two three (each on one line) Now that we have created an object with some methods, we can also take advantage of the same syntax shortcut. For example if we use for or given to populate the $_ topical variable with the $point object, we can write: given $point { say .coordinates; say .distance2center; .polar-coordinates.say; } # -> (4 3) # -> 5 # -> (5 0.643501108793284) As an exercise, you could write a method called distance_between_points that takes two points as arguments and returns the distance between them using the Pythagorean theorem. The methods of our class so far are all accessors, which means they provide a snapshot of some of the invocants attributes. If the attributes are mutable (declared with the is rw trait), we can also create some mutators, i.e., methods that can be invoked to change those mutable attributes: 224 Chapter 12. Classes and Objects class Point2D-mutable { has Numeric $.abscissa is rw; has Numeric $.ordinate is rw; # perhaps the same accessors as in the class definition above method new-ordinate (Numeric $ord) { self.ordinate = $ord; } } # Creating the Point2D-mutable object: my $point = Point2D-mutable.new(abscissa => 3, ordinate => 4); say $point; # -> Point2D-mutable.new(abscissa => 3, ordinate => 4) # Modifying the ordinate: $point.new-ordinate(6); say $point; # -> Point2D-mutable.new(abscissa => 3, ordinate => 6) 12.5 Rectangles and Object Composition Sometimes it is obvious what the attributes of an object should be, but other times you have to make decisions. For example, imagine you are designing a class to represent rectangles. What attributes would you use to specify the location and size of a rectangle? You can ignore angle; to keep things simple, assume that the rectangles edges are either vertical or horizontal. There are at least two possibilities: You could specify one corner of the rectangle (or the center), the width, and the height. You could specify two opposing corners. At this point it is hard to say whether either is better than the other, so well implement the first one, just as an example. Here is the class definition: class Rectangle has Numeric has Numeric has Point2D } { $.width; $.height; $.corner; # lower left vertex method area { return $.width * $.height } method top-left { $.corner.abscissa, $.corner.ordinate + $.height; } # other methods, e.g. for other corners' coordinates, center, etc. The new feature compared to the previous Point2D class definition is that the Rectangle class can now use the Point2D type created previously for defining the corner attribute. 12.5. Rectangles and Object Composition 225 Figure 12.2: Object diagram. The top-left method returns the coordinates of the top left angle of the rectangle. This top-left method gives us an opportunity to explain a bit more the difference between the $. and $! twigils. We have used $.corner.abscissa to obtain the abscissa of the corner, i.e., in effect an accessor invocation. We could have directly accessed the corner and height attributes of the Rectangle class and used the following method definition: method top-left { $!corner.abscissa, $!corner.ordinate + $!height; } But it would not be possible to use $!corner!abscissa or $.corner!abscissa, because abscissa is not an attribute defined in the Rectangle class, and thus cannot be accessed directly there. You can use direct access to the attribute (for example with the $!abscissa syntax) only within the class where this attribute is defined, Point2D. So, in Rectangle, we need to invoke the accessor (i.e., the syntax with $.) for obtaining the value of the corner abscissa. We can now create a Rectangle object: my $start-pt = Point2D.new(abscissa => 4, ordinate => 3); my $rect = Rectangle.new(corner => $start-pt, height => 10, width => 5); say "top-left coord.: ", $rect.top-left; # -> top-left coord.: (4 13) say "Rectangle area: ", $rect.area; # -> Rectangle area: 50 You might have noticed that the arguments passed to the Rectangle.new constructor are not in the same order as in the class definition. I did that on purpose to show that the order is unimportant because we are using named arguments. Figure 12.2 shows the state of this object. Using an object as an attribute of another object, possibly of another class, is called object composition. An object that is an attribute of another object is embedded. Object composition makes it possible to easily define nested layers of abstraction and is a powerful feature of object-oriented programming. In our geometry example, we started to define a low-level object, a Point2D instance, and then used that point to build a higher level type, Rectangle. 226 Chapter 12. Classes and Objects 12.6 Instances as Return Values Methods can return instances of another class. For example, the Rectangle class can have methods returning instances of Point2D for the other corners: method top-right-point { return Point2D.new( abscissa => $!corner.abscissa + $!width, ordinate => $!corner.ordinate + $!height ); } # other methods for other corners Notice that we dont even bother to give a name to upper right point (although we could, if we wanted); we create it with the constructor and return it on the fly. We can use the new method as follows: my $topRightPt = $rect.top-right-point; say "Top right corner: ", $topRightPt; # -> Top right corner: Point2D.new(abscissa => 9, ordinate => 13) Although this is not very useful in such a simple case, we could play it safe and declare a Point2D type for $topRightPt: my Point2D $topRightPt = $rect.top-right-point; This way, the code will raise an error if the top-right-point happens to return something other than a Point2D instance. Similarly, the find-center method invoked on a Rectangle returns a Point2D instance representing the center of the Rectangle: method find-center { Point2D.new( abscissa => $!corner.abscissa + $!width / 2, ordinate => $!corner.ordinate + $!height / 2 ); } This new method can be used as follows: say "Center = ", $rect.find-center; # -> Center = Point2D.new(abscissa => 6.5, ordinate => 8.0) 12.7 Inheritance Inheritance is probably the most emblematic feature of object-oriented programming. It is a mechanism through which it is possible to derive a class from another class. Inheritance is one of the standard ways to implement code reuse in object-oriented programming. It is also another useful way of defining successive layers of abstraction and a hierarchy of types. 12.7. Inheritance 12.7.1 227 The Pixel Class The Point2D class is very general and could be used for a variety of purposes: geometry, vector graphics, animated mangas, and so on. We may want to use it to display graphic data on a screen. For this scenario, lets create a new derived class, Pixel, adding new properties to the point, such as color, perhaps transparency, etc. Do we need to redefine all the attributes and methods for the new class? No, we dont. We can define a new class that inherits the properties of the Point2D base class and only modify what is no longer suitable or add whatever new features we need. Here, we want a new attribute to represent the pixel color and probably some new methods dealing with this new attribute. According to the most common standards, a color is defined by three integers (really three octets, i.e., integers between 0 and 255 in decimal notation), representing the red, green, and blue (RGB) components of the pixel: class Pixel is Point2D { has %.color is rw; } method change_color(%hue) { self.color = %hue } method change_color2(Int $red, Int $green, Int $blue) { # signature using positional parameters self.color = (red => $red, green => $green, blue => $blue) } The new class inherits the properties of Point2D thanks to the is Point2D trait, except possibly those that are explicitly modified (or overridden) or added in the new class. The new class is sometimes called a child class or subclass, whereas Point2D is the parent class. Creating this new class based on Point2D is called subclassing the Point2D parent class. The new child class inherits the abscissa and ordinate attributes of the Point2D parent class (and their specific type and properties if any), as well as the methods such as coordinates defined in the parent class. The child class has a new attribute (the color) and two new methods. Instantiating a Pixel object is just about as easy as before, we only need to add an additional attribute parameter in the call to the new constructor: my $pix = Pixel.new( :abscissa(3.3), :ordinate(4.2), color => {red => 34, green => 233, blue => 145}, ); say "The original pixel has the following colors: ", $pix.color; In the Pixel class definition, we have written two different methods for changing the color only to illustrate two possible syntax formats, for pedagogical purposes. The first one receives a hash as a parameter, and the second one uses positional parameters, which forces the user to remember the order (RGB) in which the arguments must be passed; this can be 228 Chapter 12. Classes and Objects a source of error and should be avoided when the number of parameters exceeds a certain limit (which will be left up to the reader). On the other hand, anyone working commonly with graphics knows by heart the standard conventional order of colors (i.e., RGB). Also, the second method has the advantage of enabling some type checks (the arguments must be integers). This is a simplified example; in real life, it may be desirable to check that the parameters are octets, i.e., integers between 0 and 255 (which could be done by adding a type constraint or defining a subset of the integer type). Using the new Pixel class is straight forward: say "Original colors: ", $pix.color; $pix.change_color({:red(195), :green(110), :blue(70),}); say "Modified colors: ", $pix.color; say "New pixel caracteristics:"; printf "\tAbscissa: %.2f\n\tOrdinate: %.2f\n\tColors: R: %d, G: %d, B: %d\n", $pix.abscissa, $pix.ordinate, $pix.color , $pix.color{"green"}, $pix.color{"blue"}; $pix.change_color2(90, 180, 30); # positional args say "New colors: \tR: {$pix.color }, G: {$pix.color }, B: {$pix.color } "; This displays the following output: Original colors: {blue => 145, green => 233, red => 34} Modified colors: {blue => 70, green => 110, red => 195} New pixel caracteristics: Abscissa: 3.30 Ordinate: 4.20 Colors: R: 195, G: 110, B: 70 New colors: R: 90, G: 180, B: 30 To tell the truth, it was not necessary to use two different method names, change_color and change_color2, as we did in the Pixel class definition to simplify matters. It would work the same way if we use these definitions: multi method change_color(%hue) { self.color = %hue } multi method change_color(Int $red, Int $green, Int $blue) { # signature using positional parameters self.color = (red => $red, green => $green, blue => $blue) } Since the multi method is defined twice, with the same name but with a different signature, the object system is able to dispatch the invocation to the right method. 12.7. Inheritance 12.7.2 229 The MovablePoint Class The $.abscissa and $.ordinate attributes of class Point2D are defaulted to read-only. After all, when you define a point in the plan, it usually has a fixed position and there is generally no reason to change its coordinates. Suppose, however, that our application is about kinematics (the branch of physics dealing with the motion of points or bodies) or is a video game. In such a case, we probably want our points (or sets of points) to move. We need a new class, MovablePoint, enabling the modification of coordinates. We dont need to redefine all the attributes and methods for the new class. Again, we can define a new class that inherits the properties of the Point2D base class and only modifies what is no longer suitable or adds whatever new features we need, for example: class MovablePoint is Point2D { has Numeric $.abscissa is rw; has Numeric $.ordinate is rw; } method move (Numeric $x, Numeric $y) { $.abscissa += $x; $.ordinate += $y; } The new class inherits the properties of Point2D thanks to the is Point2D trait, except those that are explicitly modified (or overridden) or added in the new class. Methods that exist in the parent class and are redefined in a child class are said to be overridden within that class. Here, the $.abscissa and $.ordinate attributes are redefined as read and write (through the is rw trait) and a new method, move, is defined to modify the position of a point by adding the received parameters to the coordinates of the point. Note that we have used positional parameters here for the move method. We said that it is often better for the sake of clarity to use named parameters, but we have only two parameters here; as it is fairly simple to remember that the $x parameter should come before the $y parameter, this was a good occasion to illustrate the possibility of using positional parameters. We can now test our new child class, create a MovablePoint instance, display its characteristics, move it to a different location, and display the new position: my $point = MovablePoint.new( abscissa => 6, ordinate => 7, ); say "Coordinates : ", $point.coordinates; say "Distance to origin: ", $point.distance2center.round(0.01); printf "%s: radius = %.4f, theta (rad) = %.4f\n", "Polar coordinates", $point.polar-coordinates; 230 Chapter 12. Classes and Objects say "--> Moving the point."; $point.move(4, 5); say "New coordinates: ", $point.coordinates; say "Distance to origin: ", $point.distance2center.round(0.01); printf "%s: radius = %.4f, theta (rad) = %.4f\n", "Polar coordinates", $point.polar-coordinates; This produces the following output: Coordinates : (6 7) Distance to origin: 9.22 Polar coordinates: radius = 9.2195, theta (rad) = 0.8622 --> Moving the point. New coordinates: (10 12) Distance to origin: 15.62 Polar coordinates: radius = 15.6205, theta (rad) = 0.8761 Here, when the user code invokes the coordinates, distance2center, and polar-coordinates methods, Raku finds that they do not exist in MovablePoint. But, as MovablePoint subclasses Point2D, the program looks for methods having these names in the parent class and invokes them if it finds them. If it did not find them, it might look into the parents parent to see if there are any, and so on. 12.7.3 Multiple Inheritance: Attractive, but Is It Wise? In object-oriented programming, the inheritance mechanism is a traditional way to reuse code, it is even probably the most common way to do it. A class may have several parent classes and, thus, subclass several other classes. This is what is called multiple inheritance. We might want to build a new MovablePixel class inheriting from both MovablePoint and Pixel (and, indirectly, from Point2D). Technically, you can easily do it in Raku: class MovablePixel is MovablePoint is Pixel { # ... } Now, MovablePixel is subclassing both MovablePoint and Pixel and inheriting from both parent classes. This looks very promising, but it turns out to be more complicated than expected in real situations. If there is a conflict (for example a name collision between two methods), which one shall prevail? Some mechanisms exist to handle such situations (for example in the C++ programming language), and Raku has some metaobject methods to find out about the method resolution order (MRO), but this might quickly leads to severe design problems and to really subtle or complicated bugs. In short, while multiple inheritance originally looked as a attractive idea, it turned out to be complicated to master, because it creates multiple and often implicit dependencies that are quite hard to sort out. This is the reason why, contrary to C++, relatively more recent OO programming languages such as Java (which came out not so recently, back in 1995) have decided not to implement multiple inheritance. 12.8. Roles and Composition 231 Raku does not want to forbid such things and allows you to use multiple inheritance if you wish, and it can be useful for simple cases; so dont necessarily rule it out, but remember that, contrary to early expectations, it often leads to a mess and turns out to be quite unmanageable. Raku offers better concepts for tackling such situations, as we will see shortly. 12.8 Roles and Composition Inheritance is a very powerful concept to describe a hierarchical tree of concepts. For example, you can think of a hierarchy of geometrical figures having more and more specific properties: 1. Polygon 2. Quadrilateral (a polygon with four edges and four corners) 3. Trapezoid (a quadrilateral with one pair of parallel edges) 4. Parallelogram (a trapezoid with two pairs of parallel edges and opposite sides of equal length) 5. Rectangle (a parallelogram with four right angles) 6. Square (a rectangle with all four edges of equal length) It is relatively easy to imagine a series of classes with a hierarchical inheritance tree reflecting those properties. It gets slightly more complicated, however, if we add the rhombus (a parallelogram with all sides equal), because the square is now also a rhombus with four right angles. The square class would subclass both the rectangle and the rhombus, and we might have here a possible multiple inheritance issue. Similarly, we can think of a tree of classes with nested inheritance representing various types of numbers (e.g. integer, rational, real, complex) or animals species (e.g., vertebrate, mammal, carnivoran, canid, dog, Irish setter). These are great examples for inheritance, but the real world is rarely so hierarchical, and it is often difficult to force everything to fit into such a hierarchical model. This is one of the reasons why Raku introduces the notion of roles. A role is a set of behaviors or actions that can be shared between various classes. Technically, a role is a collection of methods (with possibly some attributes); it is therefore quite similar to a class, but the first obvious difference is that a role is not designed to be instantiated as an object (although roles can be promoted into classes). The second difference, perhaps more important, is that roles dont inherit: they are used through application to a class and/or composition. 12.8.1 Classes and Roles: An Example Lets come back to vertebrates, mammals and dogs. A dog is a mammal and inherits some characteristics from the mammals, such as having a neocortex (a region of the brain), hair, and mammary glands, as well as a vertebral column, which all mammals (along with 232 Chapter 12. Classes and Objects fishes, birds, reptiles, and others) inherit from vertebrates. So far, the class hierarchy seems simple and natural. But dogs can have very different characteristics and behaviors. To quote the Wikipedia article on dogs: Dogs perform many roles for people, such as hunting, herding, pulling loads, protection, assisting police and military, companionship and, more recently, aiding handicapped individuals (italic emphasis added). Dogs can also be feral animals (i.e., animals living in the wild but descended from domesticated individuals) or stray dogs. All these additional behaviors might be added to the dog class. Similarly, a cat, another mammal, may also be a pet or a feral animal. Mustangs, North American free-roaming horses, are also feral animals, descended from once-domesticated horses; but a mustang may also be captured and brought back to domesticated state. This return to the wild of feral animals is not limited to mammals: pigeons living in our cities are often descended from oncedomesticated homing pigeons used in the past. It can even happen with invertebrates, such as swarms of honey bees. It is apparent that a hierarchical modeling of inheritance trees is not adapted to describe such behaviors. We can define classes for dogs, cats, and horses as subclasses of mammals (which itself inherits from vertebrates). Besides that, we define roles for pet or feral animals. In addition, we can create new classes subclassing the dog, horse, and cat classes and doing some specific roles; or we can assign roles to individual instances of a class. This could look like this (this is a dummy example that cannot be tested): class class class class class class class class # ... Vertebrate Mammal is Bird is Dog is Horse is Cat is Mouse is Duck is { method speak {say "vertebrate"};} Vertebrate { method speak { say "mammal" } } Vertebrate { method fly {} } Mammal { method bark {} } Mammal { method neigh {} } Mammal { method meow {} } Mammal { method squeek {} } Bird { method quack {} } role Pet-animal { method is-companion() # other methods } role Shepherd { ... } role Feral { ... } role Guide { ... } role Human-like { ... } # ... class class class class class class class {...} # # # # sheep keeper animal back to wild life blind guide animal behaving like a human Guide-dog is Dog Shepherd-dog is Dog Stray-dog is Dog Pet-cat is Cat Feral-cat is Cat Mustang is Horse Domestic-canary is Bird does does does does does does does Guide Shepherd Feral Pet-animal Feral Feral Pet-animal { { { { { { { ... ... ... ... ... ... ... } } } } } } } 12.8. Roles and Composition 233 # ... # Role can also be applied to instances: my $garfield = Pet-cat.new(...); my $mickey = Mouse.new(...); $mickey does Human-like; my $donald = Duck.new(...); $donald does Human-like; my $pluto = Dog.new(...); $pluto does Pet-animal; my $snoopy = Dog.new(...); $snoopy does Pet-animal does Human-like; A role is applied to a class or an object with the does trait (as opposed to is for inheritance). These different keywords reflect the semantic difference associated to them: composing a role into a class or an object provides this class or object with the supplementary behavior associated with the role, but it does not follow that the object receiving the role is the same thing as or of the same nature as the role. If the Pet-animal and feral roles had been defined as classes, then the Pet-cat and Feral-cat classes would have undergone double inheritance, with the potential problems associated with that. By applying a role to a class, you avoid constructing a multipleinheritance tree that is probably not really justified and can be complicated to conceptualize and difficult to maintain. Judicious use of classes and roles can lead to a model that is simpler, more natural, and closer to the real relations between the entities and behaviors under scrutiny. In addition, if you inadvertently compose several roles with two methods having the same name, this immediately raises an error (unless a method of the same name exists within the class, in which case it prevails), rather than dispatching silently to one of the two methods as in the case of multiple inheritance. In that case, naming conflicts are identified immediately (at compile time), which has the benefit of immediately finding a bug that might otherwise go unseen for a while. 12.8.2 Role Composition and Code Reuse Classes are meant for managing instances and roles are meant for managing behaviors and code reuse. The following example shows how classes and roles can play together. role Drawable { has $.color is rw; method draw { ... } } class Figure { method area { ... } } class Rectangle is Figure does Drawable { has $.width; has $.height; method area { $!width * $!height; } 234 Chapter 12. Classes and Objects method draw() { for 1..$.height { say 'x' x $.width; } } } Rectangle.new(width => 10, height => 4).draw; Please note that the ellipsis ... used in the code above is meant here to represent some code that is left to your implementation. However, this is actually valid code and it will compile and even run without any problem. The ellipsis is used to represent functionality that is not yet there but is supposed to be implemented at a later point. This will work as long as you dont invoke these methods (you would get a runtime error) or setup a situation where they would need to be defined (which would cause a compile-time error). In the case of the draw method in the Drawable role, role composition into the Rectangle class works only because draw is redefined in the Rectangle class; without this redefinition, it would have raised a compile-time error. Similarly, the method area { ... } code of the Figure class would raise a runtime error if it were called without having been redefined in the Rectangle class. The ellipsis has been used here only as a convenient way to represent code whose implementation is not important for our example because it is being redefined anyway. In real coding, it is probably best advised not to use ellipsis, except as a temporary expedient for code that is not yet developed but will be implemented. The code example above draws an ASCII rectangle: ~ raku test_drawable.raku xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx 12.8.3 Roles, Classes, Objects, and Types A role can be applied to an entire class or only to some instances of the class: role Guide { ...} class Guide-dog is Dog does Guide { ... } # Composing the Guide role into the Guide-dog class # inheriting from the Dog class my $doggy = new Dog; $doggy does Guide; # creating a Dog object # applying the role to the object Roles and classes are different, but both are or define types. This means that a role can be used as a type for a variable declaration where you might expect a class name. For example, the Guide role sketched in the code snippet above does effectively create a Guide type. So a Blind role for a human might have an attribute of Guide type, which might represent a guide-dog, a guide-horse, a human guide, or even a guiding robot. 12.9. Method Delegation class Human { has Dog $dog; } role Blind { has Guide $guide; } 235 # May contain any dog, with or without # a guide role # May contain any Guide type, whether # a dog, a horse, a human or a robot A number of Raku built-in types are defined by roles and not by classes, such as IO, Iterable, Iterator, Numeric, Rational, Real, etc. 12.9 Method Delegation Delegation is another way to link an object to another piece of code. The delegation technique has been relatively well studied at the theoretical level and implemented in a few specialized research languages, but mainstream generalist languages implementing delegation are rather rare. Rather than defining methods in a class or in a role, the idea is to invoke methods belonging to another object, as if they were methods of the current class. In Raku, delegation may be performed at the level of a class or a role. A delegated object is simply an attribute defined in the class or in the role with the handles keyword which makes it possible to specify which methods of the delegated object may be used in the current class: class BaseClass { method Don-Quijote() { "Cervantes" } method Hamlet() { "Shakespeare" } method Three-Sisters () { "Chekhov" } method Don-Carlos() { "Schiller" } } class Uses { has $.base is rw handles < Don-Quijote Hamlet Three-Sisters >; } my $user = Uses.new; $user.base = BaseClass.new(); # implementing an object-handler say $user.Don-Quijote; say $user.Hamlet; say $user.Three-Sisters; say $user.Don-Carlos; This displays the following output: Cervantes Shakespeare Chekhov Method 'Don-Carlos' not found for invocant of class 'Uses' in block at delegate.raku line 16 236 Chapter 12. Classes and Objects The program properly displays the names of writers returned by the first three methods, because they have been sort of imported into the Uses class, but it fails on the last one, because Don-Carlos is not part of the handlers list. The error on the last method is a runtime exception and the program would stop running there even if there were some more correct code afterward. Note that the Uses class does not know from where the methods will be imported; it only knows about the names of the methods that will be imported. It is only when the $user object is created and the $user.base attribute is added to it that the object is dynamically associated with the methods defined in BaseClass. By the way, this process could be done in just one step: my $user = Uses.new( base => BaseClass.new() ); There is no need to enumerate the methods to be handled. The Uses class can import all the methods of BaseClass: class Uses { has $.base is rw handles BaseClass; } This will work as before, except of course that it will not fail on the Don-Carlos method this time, since this method is also imported now: Cervantes Shakespeare Chekhov Schiller 12.10 Polymorphism Polymorphism is a way to supply a common or close interface to different types. In a certain way, the inheritance examples studied previously offer a form of polymorphism: the coordinates, distance2center, and polar-coordinates methods are polymorphic, since they can apply to Point2D, movablePoint, and pixel types. But these are trivial forms of polymorphism. We will speak of polymorphism when the relevant methods or functions are doing something different from each other, at least at the implementation level, even if they share the same name and interface. Outside of object-oriented programming, Rakus multi subroutines implement a form of polymorphism, since they can behave differently depending on the type and number of their arguments. Within the OOP context, it is often the type of the invocant (its class or possibly one of its roles) that will determine, usually at runtime, which of the possible methods will be invoked. For example, we might want to create a new class for points in a three-dimensional space. The methods will have to be different, but it seems interesting to offer the user an interface that is the same (or almost) as for two-dimensional points: class Point3D { has Numeric $.x; 12.10. Polymorphism 237 has Numeric $.y; has Numeric $.z; } method coordinates () { # accessor to the 3 coordinates return $.x, $.y, $.z } method distance2center () { return ($.x ** 2 + $.y ** 2 + $.z ** 2) ** 0.5 } method polar-coordinates () { return self.spherical-coordinates; } method spherical-coordinates { my $rho = $.distance2center; my $longitude = atan2 $.y, $.x; # theta my $latitude = acos $.z / $rho; # phi return $rho, $longitude, $latitude; } method cylindrical-coordinates { # ... } The methods in this new class are not the same as those in Point2D, but methods with a similar semantics have the same name; it is thus possible to use either class without being lost with different names. The distance2center method has exactly the same interface. The coordinates method returns a list of three values instead of two, but the calling convention is the same. Note that it might also have been possible to design Point2D so that this method would return a third zero value, in order to have exactly the same interface (after all, a point in the plane might be considered as a point in the 3D space with a zero height); complying to exactly the same interface is not mandatory, but only a possible implementation decision that might make for a more intuitive interface. The notion of polar coordinates does not have a well-defined meaning in a 3D space, but I have chosen here to keep the name in our interface because it is intuitively quite similar to the idea of spherical coordinates; it does nothing more than invoke the spherical-coordinates method on its invocant and to return the return values. Please note that mathematicians, physicists, astronomers, engineers, geographers, and navigators all use the same basic system for spherical coordinates, but their conventions are different concerning the origin, angle range, angle measurement units and rotation direction, and the name of the various values or symbols associated with them. So you might find some different formulas in a textbook. The conventions and formulas we have used here are commonly used in geography and some branches of mathematics. A real generalpurpose class might have to take these varying conventions into account and implement the necessary conversions. 238 Chapter 12. Classes and Objects 12.11 Encapsulation Encapsulation is the idea of hiding the data and the code of a library or a module from the user. It is not specific to object-oriented programming, but it is a fundamental concept of OOP. In object-oriented programming, encapsulation consists of protecting the data in an object from being tampered with directly (and possibly made inconsistent) by the user, who can access such data only through the means of methods. This is achieved by providing to the user methods that are commonly called accessors (or getters) and mutators (or setters). This makes it possible to ensure that the object properties will be validated by its methods. Encapsulation is a strong form of data abstraction and procedural abstraction. Seen from the outside, an object is a black box having some specified properties and behaviors. This way, these properties and behaviors are hidden from the user. Theyre not hidden in the sense that the user cannot know about them (at least in the open-source world, it is easy to know that), but hidden in the sense that it is usually not possible to use that knowledge to bypass the supplied interface. This means that the internal implementation of the object may change without having to modify the external behavior. If you are going to use insider knowledge, your code will probably break when the internal implementation is modified, so dont do that. Various programming languages dont have the same rules for guaranteeing encapsulation. Some are stricter than others, some are less restrictive for read access than for write access, others dont make such a distinction but rather rely on the visibility level specified for an attribute, for example public or private (with sometimes an intermediate protected level). Raku lets you choose the encapsulation model you want to apply to your objects and attributes. All attributes are private. If you declare a class as follows: class Point2D { has $!abscissa; has $!ordinate; # ... method value_x { return $!abscissa } method value_y { return $!ordinate } } the $!x and $!y coordinates will be accessible only from within the class. This is why we have added accessor methods. In addition, the attributes are immutable by default. But as we have seen earlier, if you declare this class as follows: class Point2D { has $.abscissa; has $.ordinate; # ... } the coordinates will still be private attributes, but Raku will automatically generate accessor methods having the same names as the attributes, so that it will be possible to access them from outside the class almost as if they were public: 12.11. Encapsulation 239 class Point2D { # ... } my $point = Point2D.new(abscissa => 2, ordinate => 3); say $point.abscissa; # -> 2 Whether the attribute is mutable or not is managed separately by the is rw trait. In brief, Raku offers a default access mode, but you can fine-tune it and what you need. 12.11.1 Private Methods Methods are the normal way to use objects, whether with read-only or read and write access. They usually form the interface of a class, that is the part of the class that is made public and available to programmers wishing to use them. It is thus natural and legitimate for methods to be public, i.e., accessible from outside the class. But a class may also contain numerous methods that are part of the internal cooking recipes of the class, i.e., the way it does things internally, and that are not meant to be used from outside the class. It is possible to prevent their use from outside the class by making these methods private. A Raku private method is prefixed with an exclamation mark: method !private-behavior($x, $y) { ... } You will also need to use an exclamation mark to call them: $my-object!private-behavior($val1, $val2) Private methods are really internal to a given class. In particular, they are not inherited by child classes. 12.11.2 Constructing Objects with Private Attributes Constructing objects with private attributes raises a little difficulty. Lets consider the following program: class Point3D { has $.x; has $.y; has $!z; }; method get { return ($!x, $!y, $!z); } my $a = Point3D.new(x => 23, y => 42, z => 2); say $_ for $a.get; 240 Chapter 12. Classes and Objects In this example, we have declared $.x and $.y as public (so to speak) attributes, and $!z as a truly private attribute. Running this code displays this: 23 42 (Any) Oops, what is going on? It seems that the get method is not able to read $!z, since it returns an undefined value. This method is defined within the class and it should be able to access this attribute. In fact, get is not the problem, it is $!z that is not defined within the object, because it hasnt been properly initialized during object construction. The guilt lies with the new implicit constructor which, by default, initializes only public attributes. Here, the simplest solution is probably to add a BUILD submethod in the class definition. A submethod is a public method of a class that is not inherited in its child classes. Semantically, it is really equivalent to a subroutine, but it is called with a method syntax (hence the name). Submethods are especially useful to perform object construction and destruction tasks that should not be inherited by subclasses, as well as for tasks that are so specific to a given type that classes derived from it will almost surely have to redefine them. Initializing private attributes at object instantiation might look like this: class Point3D { has $.x; has $.y; has $!z; }; submethod BUILD (:$!x, :$!y, :$!z) { say "Initialization"; $!x := $!x; $!y := $!y; $!z := $!z; } method get { return ($!x, $!y, $!z); } my $a = Point3D.new(x => 23, y => 42, z => 2); say $_ for $a.get; The program now works as desired and displays all three attributes: Initialization! 23 42 2 This works because the default new constructor, a method defined in the Mu ultimate superclass and inherited by default by any Raku class, calls the default BUILD submethod. If we 12.11. Encapsulation 241 redefine BUILD in our class, it will supersede the default one called by new. By redefining BUILD, we force the constructor to take into account the private attribute that was not used previously. Quite a bit of simplification is possible. Since passing arguments to a routine binds the arguments to the parameters, a separate binding step is unnecessary if the attributes are used as parameters. Hence, the BUILD submethod in the example above could also have been written simply as: submethod BUILD(:$!x, :$!y, :$!z) { say "Initialization!"; } While we are speaking about the intricacies of object construction, note that since new is a method inherited from the Mu superclass, you can override it if you wish. The default new constructor can only be used with named arguments. Assuming you absolutely want to use positional parameters, you could override new with your own method, like so: class Point2D { has Numeric $.abscissa; has Numeric $.ordinate; }; method new ($x, $y) { self.bless(abscissa => $x, ordinate => $y); } method coordinates { # accessor to both coordinates return (self.abscissa, self.ordinate) } # other methods my $point = Point2D.new(3, 5); say $_ for $point.coordinates; This will duly display the two coordinates. bless is a low-level method for object construction, inherited from Mu and called automatically when you invoke new to construct an object. You usually dont need to know about it, except when you want to write your own custom constructor. You can give the constructor a different name than new, for example: class Point2D { has Numeric $.abscissa; has Numeric $.ordinate; method construct ($x, $y) { self.bless(abscissa => $x, ordinate => $y); } method coordinates { # accessor to both coordinates return (self.abscissa, self.ordinate) } # other methods 242 Chapter 12. Classes and Objects }; my $point = Point2D.construct(3, 5); say $_ for $point.coordinates; Think twice, though, before you override new or create your own custom constructor with a different name, as it may make it more complicated to subclass your Point2D class. 12.12 Interface and Implementation One of the goals of object-oriented design is to make software more maintainable, which means that you can keep the program working when other parts of the system change, and modify the program to meet new requirements. A design principle that helps achieve that goal is to keep interfaces separate from implementations. For objects, that means that the public interface of the methods provided by a class should not depend on how the attributes are represented. For example, we designed a Point2D class in which the main attributes were the points Cartesian coordinates. We may find out that, for the purpose of our application, it would be easier or faster to store the points polar coordinates in the object attributes. It is entirely possible to change the internal implementation of the class, and yet keep the same interface. In order to do that, we would need the constructor to convert input parameters from Cartesian into polar coordinates, and store the latter in the object attribute. The polar-coordinates method would return the stored attributes, whereas methods returning the Cartesian coordinates may have to do the backward conversion (or may perhaps be stored separately in private attributes). Overall, the change can be made with relatively heavy refactoring of the Point2D class, but users of the class would still use the same interface and not see the difference. After you deploy a new class, you might discover a better implementation. If other parts of the program are using your class, it might be time-consuming and error-prone to change the interface. But if you designed the interface carefully, you can change the implementation without changing the interface, which means that other parts of the program dont have to change. 12.13 Object-Oriented Programming: A Tale Most tutorials and books teaching object-oriented programming tend to focus on the technical aspects of OOP (as we have done in this chapter so far), and thats a very important part of it, but they sometimes neglect to explain the reasons for it. They say how, but not why. Weve tried to explain the why (and hopefully succeeded in doing so), but this section attempts to explain OOP from the standpoint of the reasons for it and its benefits, independently of any technical consideration, in the form of a parable (the code examples are only pseudocode and are not supposed to compile, let alone run). 12.13. Object-Oriented Programming: A Tale 12.13.1 243 The Fable of the Shepherd Once upon a time, there was a sheep farmer who had a flock of sheep. His typical workday looked like this: $shepherd.move_flock($pasture); $shepherd.monitor_flock(); $shepherd.move_flock($home); Eventually, due to successful wool sales, he expanded his farming activities and his day became like this: $shepherd.move_flock($pasture); $shepherd.monitor_flock(); $shepherd.move_flock($home); $shepherd.other_important_work(); But now the shepherd wanted to devote more time to other_important_work(), so he decided to hire a minion to handle the sheep-related work, so the work was now split like this: $shepherd-boy.move_flock($pasture); $shepherd-boy.monitor_flock(); $shepherd-boy.move_flock($home); $shepherd.other_important_work(); This did give the shepherd more time for other_important_work(), but unfortunately the $shepherd-boy had a tendency to cry wolf, so the farmer had to replace him with a new assistant: $sheep-dog.move_flock($pasture); $sheep-dog.monitor_flock(); $sheep-dog.move_flock($home); $shepherd.other_important_work(); $sheep-dog was more reliable and demanded less pay than $shepherd-boy, so this was a win for the farmer. 12.13.2 The Moral We can learn a few things from this parable. 12.13.2.1 Delegation To handle complexity, delegate to a suitable entity, e.g., the farmer delegates some of his work to $shepherd-boy. 244 Chapter 12. Classes and Objects 12.13.2.2 Encapsulation Tell objects what to do, rather than micro-manage, e.g.: $sheep-dog.monitor_flock(); rather than something like: $sheep-dog.brain.task.monitor_flock; At a high level, we do not particularly care what the internals of the object are. We only care what the object can do. An object becomes harder to change the more its internals are exposed. 12.13.2.3 Polymorphism $sheep-dog and $shepherd-boy both understood the same commands, so replacing the latter with the former was easier than it would have been otherwise. The fable of this section is adapted from a post by Arunbear on the RakuMonks website: http: // www. perlmonks. org/ ?node_ id= 1146129 . Thanks to Arunbear for authorizing me to reuse it. 12.14 Debugging This section is about using a debugger, a program that is designed to help you to debug your programs. What? There is a tool to debug my programs, and youre telling me only now? you might complain. Well, its not quite that. A debugger is not going to do the debugging for you; youll still have to do the hard investigation work, but a debugger can help you a lot in figuring out why your program isnt doing what you think it should be doing. Or, rather, why what your program is doing isnt quite what you want it to do. Debuggers are a bit like people with a strong personality: some people love them and others hate them. Often, people who dont like debuggers simply never took the time to learn how to use them, but there are also many expert programmers who dont like them and whom we cant suspect of not having seriously tried. Whether you like debuggers or not is probably a matter of personal taste, but they can provide an invaluable help, if you know how to use them. 12.14.1 The Raku Debugger Rakudo ships with an interactive debugger that you call with the raku-debug command (or, on some installs at least, raku-debug-m). You can just fire this command, followed by the name of the program to be debugged, just as you would normally use raku with the name of a program to run the program. One word of warning: you can run the debugger on a program only if the program compiles with no errors; a debugger is not aimed as finding compile-time error, but only execution or semantic errors. Once youve launched the debugger, you will see something like this: 12.14. Debugging 245 >>> LOADING while_done.raku + while_done.raku (1 - 3) | while True { | my $line = prompt "Enter something ('done' for exiting)\n"; | last if $line eq "done"; > This says that it is loading the while_done.raku program, and displays the first lines of the program; the last line at the bottom (>) is a prompt where you can enter some commands. The program is stopped at the first statement that actually does something and waits for your input. The code line that is waiting to be executed is highlighted in a different color. 12.14.2 Getting Some Help The first command you probably want to issue is h, which will display the debugger help and return to the prompt. Below, we have omitted most of the output for brevity: > h s so [...] q[uit] > single step, stepping into any calls step to next statement, stepping over any calls step out of the current routine exit the debugger Take the time to issue that command and to read the various possible instructions you can enter. We will describe the most common ones. As you can see above, just use q or quit to exit the debugger. 12.14.3 Stepping Through the Code The main characteristic of a debugger is that it lets you run the program step by step. Each time you hit the Enter key, the program will move forward one step (e.g., one code line). It will enter into any subroutine if the code line is a subroutine call, but you can step over the subroutine call by issuing the s command at the debugger prompt: this will run the subroutine and bring you to the first code line after the subroutine call (and any nested call of other subroutines) is over. If you entered into a subroutine but are no longer interested in stepping through it, just issue the so command to step out of it. At any point through that process, you can look at the content of variables or even call methods on them. To view a variable, just type its name and then press Enter: > $line "foo" You can also view an array or a hash, or use the index or the key, for example @array[10] or %hash{"bar"}), to visualize one specific item of the array or the hash. You may also use s (or say) or p (or print) to evaluate and display an expression in the current scope. 246 Chapter 12. Classes and Objects 12.14.4 Stopping at the Right Place with Breakpoints You might find it tedious to run through the program step by step until you get to the interesting part. As it happens, you can get there immediately using a breakpoint. For adding a breakpoint, you type bp add line, where line is the line number where you want the program to stop running and resume stepping line by line. Then you enter the r command and the program will run until it reaches one of the breakpoints that you have set. The execution will also stop if the program runs into an exception; in that case, you can still access variables to try to figure out what went wrong. If it does not hit a breakpoint or an exception, it will run to the end. You can view all breakpoints (bp list), remove one breakpoint (bp rm line), or remove all breakpoints (bp rm all). You can also set a breakpoint in another file (for example if you are using a module) by using the following syntax: bp add file:line, where file is the file name. 12.14.4.1 Youre all set to start using the debugger You probably know enough by now to make good use of the Raku debugger, step through your program and find out where it does something that isnt what you intended. It wasnt so much to learn, was it? Try it! Well cover a couple of additional goodies, though. 12.14.5 Logging Information with Trace Points It is possible to set trace points on specific lines of code and variables (or expressions), with the command tp add line $var. This will record the value of $var each time the program hits the chosen line. Then you simply run the program for a while and, at some point, you can visualize how the variable changed over time, using the command tp show. For example, we used it to log the variable $rotated-word in the solution to the Caesars cipher exercise (see Subsection A.5.9) for the ABCDabcd input string with a rotation of 25 letters; the tp show command displayed how the coded output string was progressively populated letter by letter: > tp show >>> rotate.raku:23 * * Z * ZA * ZAC * ZACB * ZACBz * ZACBza * ZACBzab 12.14.6 Stepping Through a Regex Match The debugger can also provide useful information when the code is trying to match a regex. For example, suppose were running a program under the debugger in which we have the following code: 12.15. Glossary 247 "foobar" ~~ /f.+b/; If you run the regex step by step, color highlighting will show atom by atom where it is in the regex and which part of the string has been matched. (We cant show the color highlighting here, but you should try it to see it.) With the above regex, youll see that the regex engine tries to match the f of the pattern and that it finds an f at the beginning of the string; next, youll see that the regex engines tries to match the .+ subpattern and that it matches the whole string; then, when the regex engine tries to match the final b of the pattern, youll see that the regex engine backtracks and gives away the r and then the a; finally, the regex engine succeeds with foob. If you have difficulty understanding how regexes work or are mystified by backtracking, just run the debugger on a few regexes and observe whats going on step by step. You dont even have to write a program; you can use it as a one-liner. For example, to test the above regex as a one-liner under Windows, just type the following command at the prompt: C:\Users\Laurent>raku-debug-m -e "'foobar' ~~ /f.+b/;" As usual, change double quotes to single quotes and the other way around if you are using a Unix-like platform. Our final word on the debugger: remember you can always hit h to get help on the command you need. 12.15 Glossary Object An entity that encloses its state (attributes) and its behavior (methods). Class A programmer-defined type. A class definition creates a new type object (a form of abstract definition) and makes it possible to instantiate concrete objects representing real data. Method A special kind of subroutine defined within a class or a role, that can be called using the dot notation syntax Type object An object that contains information about a programmer-defined type. The type object can be used to create instances of the type. Instance An object that belongs to a class and contains real data. Instantiate To create a new object. Attribute A state property akin to a variable within an OOP framework. An instance attribute is one of the named values associated with an object. Class attributes are variables associated with the whole class. Embedded object An object that is stored as an attribute of another object. Object composition Using an object as part of the definition of another object, especially using an object as an attribute of another object. Object diagram A diagram that shows objects, their attributes, and the values of the attributes. 248 Chapter 12. Classes and Objects Role A collection of methods quite similar to a class but that is not designed to build objects. A role contains methods that can be applied to a class or an object to add new behaviors to them. Polymorphic Pertaining to a function that can work with more than one type. Encapsulation The principle that the interface provided by an object should not depend on its implementation, in particular the representation of its attributes. This is also called information hiding. Inheritance The ability to define a new class that is a modified version of a previously defined class. Parent class The class from which a child class inherits. Child class A new class created by inheriting from an existing class; also called a subclass. Subclassing Creating a child class derived from an existing parent class. Override when the method of a parent class is redefined in a child class, it is said to be overridden within that child class. Multiple inheritance A situation in which a child class is derived and inherits from more than one parent class. Delegation Defining a class or a role in which it is possible to invoke methods belonging to another object. Chapter 13 Regexes and Grammars Regular expressions or regexes were introduced in Sections 7.5 to 7.9. You might want to review those sections before reading this chapter if you dont remember much about regexes. You dont need to remember the details of everything we covered earlier and we will explain again briefly specific parts of the functionality that we will be using, but you are expected to understand generally how regexes work. 13.1 A Brief Refresher Regexes, as we have studied them so far, are about string exploration using patterns. A pattern is a sequence of (often special) characters that is supposed to describe a string or part of a string. A pattern matches a string if a correspondence can be found between the pattern and the string. For example, the following code snippet searches the string for the letter a, followed by any number (but at least one) of letters b or c, followed by zero or more digits followed by a B or a C: my $str = "foo13abbccbcbcbb42Cbar"; say ~$/ if $str ~~ /a <[bc]>+ (\d*) [B|C]/; say ~$0; # -> abbccbcbcbb42C # -> 42 This code uses the ~~ smart match operator to check whether the $str string matches the /a <[bc]>+ (\d*) [B|C]/ pattern. Remember that spaces are usually not significant in a regex pattern (unless specified otherwise). The pattern is made of the following components: a: a literal match of letter a <[bc]>+: the <[bc]> is a character class meaning letter b or c; the + quantifier says characters matching the character class b or c can be repeated one or more times 250 Chapter 13. Regexes and Grammars (\d*): the \d atom is a digit character class, the * quantifier means 0 or more occurrences of the previous atom, and the enclosing parentheses request a capture of these digits (if any) into the $0 variable (a special variable that is really a shortcut for $/[0]) [B|C]: B|C is an alternation (either a B or a C), and the square brackets regroup this alternation into one subpattern (and also enable proper precedence). If the match is successful (as is the case in this example), the result is stored into the match object, $/. Printing ~$/ displays a stringified version of the match object. And printing $0 (or $/[0]) displays the capture (part of the match that is between parentheses, in this case the number 42). This is what might be called low-level matching: pattern recognition is done mostly at the individual character level. Raku offers ways to group and name regex patterns so that these individual patterns can then be used as building blocks for higher level matching: recognizing words and sequences of words (rather than just characters), for the purpose of performing what is called lexical analysis (or lexing) and grammatical analysis (or parsing) on a piece of text. This chapter is mostly devoted to this higher type of matching, leading to the creation of full-fledged grammars that can analyze structured text such as XML or HTML texts, JSON or YAML documents, or even computer programs: Raku programs are actually parsed using a Raku grammar written in Raku. Grammars are a very important topic in computer science, but, obviously, most programmers dont commonly write full-fledged grammars for parsing programming languages. However, writing a simple grammar and a simple parser might be, or perhaps should be, a much more common task. Quite often, people spend a lot of effort at deciphering a simple configuration file with low-level techniques, whereas writing a simple parser might be a lot easier and much more efficient. Raku offers all the tools to do that very easily. Sometimes, you also need to develop a domain-specific language (DSL), i.e., a usually relatively small sublanguage (a.k.a. slang) adapted to a specific field of knowledge (scientific, engineering, business, art, or other) with its own conventions, symbols, operators, and so on. With a grammar and Rakus ability to create its own operators, you can often express specialized knowledge within the terminology framework of subject-matter experts. 13.2 Declarative Programming Both regexes and grammars are examples of yet another programming paradigm that we havent really explored so far: declarative programming. This is a programming model in which, contrary to ordinary imperative or procedural programming, you dont state how to do something and dont choose your control flow. Rather, you specify a set of definitions, rules, properties, and possibly some constraints and actions, and let the program apply those to derive some new information about the input data. This form of programming is widely used in logic programming (e.g., Prolog), artificial intelligence, expert systems, data analysis, database query languages (e.g., SQL), text and source code recognition (e.g., Lex and Flex), program compilation (e.g., Yacc or Bison), configuration management, makefiles, and also in some ways functional programming. 13.3. Captures 13.3 251 Captures As we noted in the regex examples at the beginning of this chapter, round parentheses not only group things together, but also capture data: they make the string matched by the subpattern within the parentheses available as a special variable: my $str = 'number 42'; say "Number is $0" if $str ~~ /number \s+ (\d+) /; # -> Number is 42 Here, the pattern matched the $str string, and the part of the pattern within parentheses was captured in the $0 special variable. Where there are several parenthesized groups, they are captured in variables named $0, $1, $2, etc. (from left to right): say "$0 $1 $2" if "abcde" ~~ /(a) b (c) d (e)/; # -> a c e This is fine for simple captures, but the numbering of captures can become tedious if there are many captures and somewhat complicated when there are nested parentheses in the pattern: if 'abc' ~~ / ( a (.) (.) ) / { say "Outside: $0"; say "Inside: $0[0] and $0[1]"; } # Outside: abc # Inside: b and c When it gets complicated, it is often better to use another feature called named captures. The standard way to name a capture is as follows: if 'abc;%' ~~ / $ = \w+ / { say ~$ ; # abc } The use of the named capture, $ , is a shorthand for accessing the $/ match object as a hash, in other words: $/{ 'capture_name' } or $/ . Named captures can be nested using regular capture group syntax: if 'abc' ~~ / $ =( a $ =(.) $ =(.) ) / { say "Overall: $ "; # Overall: abc say "Part 1: $ "; # Part 1: b say "Part 2: $ "; # Part 2: c } Assigning the match object to a hash gives you easy programmatic access to all named captures: if 'abc' ~~ / $ =( a $ =(.) $ =(.) ) / { my %capture = $/.hash; say ~%capture ; # -> abc for kv %capture -> $key, $val { say $key, " ", ~$val; # -> part2 c \n part1 b } } 252 Chapter 13. Regexes and Grammars But you might as well do the same thing directly on the match object without having to perform an extra hash assignment: if 'abc' ~~ / $ =( a $ =(.) $ =(.) ) / { say "Overall: $ "; # -> Overall: abc for kv % -> $key, $val { say $key, " ", ~$val; # -> part2 c \n part1 b } } Remember that, in the above code, $ is really a shortcut for $/ , i.e., for a hash type of access to the $/ match object. There is, however, a more convenient way to get named captures which is discussed in the next section. 13.4 Named Rules (a.k.a. Subrules) It is possible to store pieces of regexes into named rules. The following example uses a named regex, which is one of the kinds of named rules, to match a text line: my regex line { \N* \n } # any number of characters other # than new line, followed by 1 new line if "abc\ndef" ~~ / def/ { say "First line: ", $ .chomp; # First line: abc } Notice that the syntax with a block of code is akin to a subroutine or method definition. This is not a coincidence; we will see that named rules are very similar to methods. Notably, rules can call each other (or even sometimes call themselves recursively) just like methods and subroutines, and we will see that this is a very powerful and expressive feature. A named regex can be declared with my regex name { regex body }, and called with . As you can see in the example above, a successful named regex creates a named capture with the same name. If you need a different name for the capture, you can do this with the syntax . In this example, we call the same named regex twice and, for convenience, use a different name to distinguish the two captures: my regex line { \N* \n } if "abc\ndef\n" ~~ / / { say "First line: ", $ .chomp; # -> First line: abc say "Second line: ", $ .chomp; # -> Second line: def print $_.chomp for $ .list; # -> abc def } Here, we have used chomp method calls to remove the new line characters from the captures. There is in fact a way to match on the new line character but exclude it from the capture: 13.4. Named Rules (a.k.a. Subrules) 253 my regex line { \N* )> \n } if "abc\ndef\n" ~~ / / { say "First line: ", ~$ ; # -> First line: abc say "Second line: ", ~$ ; # -> Second line: def print $ .list; # -> abc def } This relatively little-known token, ")>," marks the endpoint of the matchs overall capture. Anything after it will participate to the match but will not be captured by the named regex. Similarly, the "<)" token indicates the start of the capture. Named regexes are only one form (and probably not the most common) of the named rules, which come in three main flavors: Named regex, in which the regex behaves like ordinary regexes Named tokens, in which the regex has an implicit :ratchet adverb, which means that there is no backtracking Named rules, in which the regex has an implicit :ratchet adverb, just as named tokens, and also an implicit :sigspace adverb, which means that whitespace within the pattern (or, more specifically, between word characters) is not ignored In the two examples above, we did not need the regexes to backtrack. We could (and probably should) have used a named token instead of a named regex: my token line { \N* \n } if "abc\ndef" ~~ / def/ { say "First line: ", $ .chomp; } # First line: abc But, for a rule to match, we would have to remove the space from within the pattern: my rule line { \N*\n } if "abc\ndef" ~~ / def/ { say "First line: ", $ .chomp; } # First line: abc Collectively, these three types of named rules are usually referred to as rules, independently of the specific keyword used for their definition. Remember the various regexes we experimented for extracting dates from a string in Subsection 7.8.1 (p. 116)? The last example used subpatterns as building blocks for constructing the full pattern. We could now rewrite it, with the added feature of recognizing multiple date formats, as follows: my $string = "Christmas : 2016-12-25."; my token year { \d ** 4 } my token month { 1 <[0..2]> || 0 <[1..9]> }; # 10 to 12 # 01 to 09 254 Chapter 13. Regexes and Grammars my token day { (\d ** 2) {1 <= $0 <= 31 }> } my token sep { '/' || '-' } my rule date { ( ) $0 || ( ) $0 || \s ',' } if $string ~~ / / { say ~$/; say "Day\t= " , ~$/ ; say "Month\t= " , ~$/ ; say "Year\t= " , ~$/ ; } # # # # -> -> -> -> 2016-12-25 25 12 2016 The first four named tokens define the basic building blocks for matching the year, the month, the day, and possible separators. Then, the date named rule uses these building blocks to define an alternation between three possible date formats. This code checks that the day in the month is between 1 and 31 and that the month is between 01 and 12, and this is probably sufficient to recognize dates in a text in most cases, but this would match 2016-11-31 as a date, although November only has 30 days. We may want to be a little bit stricter about valid dates and prevent that by adding a negative code assertion to the date named rule: my rule date { [ } ( ) $0 || ( ) $0 || \s ',' ] > 30 and $ == 2|4|6|9|11}> This is better, but we can still match an invalid date such as 2016-02-30. Exercise 13.1. As an exercise, change the code assertion to reject a Feb. 30 date. If you feel courageous, you might even want to check the number of days in February depending on whether the date occurs in a leap year. You may also want to try to define and test other date formats. Solution: A.10.1 Rules can (and usually should) be grouped in grammars; thats in fact what they have been designed for. 13.5 Grammars Grammars are a powerful tool used to analyze textual data and often to return data structures that have been created by interpreting that text. For example, any Raku program is parsed and executed using a Raku grammar written in Raku, and you could write a grammar for parsing (almost) any other programming language. To tell the truth, programmers rarely write grammars for parsing programming languages. But grammars are very useful for performing many tasks that are much more common than parsing programs. 13.5. Grammars 255 If you ever tried to use regexes for analyzing a piece of HTML (or XML) text1 , you probably found out that this is quickly becoming next to impossible, except perhaps for the most simple HTML data. For analyzing any piece of such data, you need an actual parser which, in turn, will usually be based on an underlying grammar. If you didnt like grammar in school, dont let that scare you off grammars. Raku grammars are nothing complicated; they just allow you to group named rules, just as classes allow you to group methods of regular code. A grammar creates a namespace and is introduced with the keyword grammar. It usually groups a number of named rules, in the same way a class groups a number of methods. A grammar is actually a class that inherits from the Grammar superclass, which provides methods such as parse to analyze a string and .parsefile to analyze a file. Moreover, you can actually write some methods in a grammar, and even import some roles. And, as we shall see, grammars are often associated with some actions classes or actions objects. Unless told otherwise, the parsing methods will look for a default rule named TOP (which may be a named regex, token, or rule) to start the parsing. The date parsing rules used above might be assembled into a grammar as follows: grammar My-date { rule TOP { \s*? [ ( ) $0 || ( ) $0 || \s ',' ] \s* > 30 and $ == 2|4|6|9|11)}> } token year { \d ** 4 } token month { 1 <[0..2]> || 0 <[1..9]> } token day { (\d ** 2) {1 <= $0 <= 31 }> } token sep { '/' || '-' } } for " 2016/12/25 ", " 2016-02-25 ", " 31/04/2016 " -> $string { my $matched = My-date.parse($string); say ~$matched if defined $matched; } This will print out: 2016/12/25 2016-02-25 The code assertion within the TOP rule prevents invalid dates such as 31/04/2016 from being matched; you would need to add some code for handling the end of February dates, as we did in the solution to the previous exercise (see Subsection A.10.1) if this is important. You may want to do it as an exercise. Besides that, this code is not very different from our earlier code, but there are a few changes that are significant. 1 Dont try to do it. Now, I warned you: just dont do it. 256 Chapter 13. Regexes and Grammars I renamed the date rule as TOP because this is the default name searched by parse for the top-level rule. A grammar creates its own namespace and lexical scope, and I no longer need to declare the rules with the my declarator (which is required for rules declared outside of a grammar). Within a grammar, the order in which the rules are defined is generally not relevant, so that I could define the TOP rule first, even though it uses tokens that are defined afterwards (which again would have not been possible with rules used outside a grammar). This is important because, within a grammar, you can have many rules that call each other (or rules that call themselves recursively), which would be impractical if the order of the rule definitions mattered. If youre parsing the input string with the .parse method, the TOP rule is automatically anchored to the start and end of the string, which means that the grammar has to match the whole string to be successful. This is why we had to add patterns for spaces at the beginning and at the end of our TOP rule to match our strings which have some spaces before and after the date itself. There is another method, .subparse, which does not have to reach the end of the string to be successful, but we would still need to have the space pattern at the beginning of the rule. 13.6 Grammar Inheritance A grammar can inherit from another grammar, just as a class can inherit from another class. Consider this very simple (almost simplistic) grammar for parsing a mail message: grammar Message { rule TOP { $= +? } rule greet { [Hi||Hello||Hey] $ =\S+? ',' } rule end { Later dude ',' $ =.+ } token line { \N* \n} } We can test it with the following code: my $msg = "Hello Tom, I hope you're well and that your car is now repaired. Later dude, Liz"; my $matched = Message.parse($msg); if defined $matched { say "Greeting \t= ", ~$matched .chomp; say "Addressee\t= $matched "; say "Author \t= $matched "; say "Content \t= $matched"; } This will print out the following: Greeting Addressee Author Content = = = = Hello Tom, Tom Liz I hope you're well and that your car is now repaired. 13.7. Actions Objects 257 Suppose now that we want a similar grammar for parsing a more formal message and we figure out that we could reuse part of the Message grammar. We can have our new child grammar inherit from the existing parent: grammar FormalMessage is Message { rule greet { [Dear] $ =\S+? ',' } rule end { [Yours sincerely|Best regards] ',' $ =.+ } } The is Message trait in the header tells Raku that FormalMessage should inherit from the Message grammar. Only two rules, greet and end, need to be redefined; the others (the TOP rule and the line token) will be inherited from the Message grammar. Lets try some code to run it: my $formal_msg = "Dear Thomas, enclosed is our invoice for June 2016. Best regards, Elizabeth."; my $matched2 = FormalMessage.parse($formal_msg); if defined $matched2 { say "Greeting \t= ", ~$matched2 .chomp; say "Addressee\t= $matched2 "; say "Author \t= $matched2 "; say "Content \t= $matched2"; } This will print: Greeting Addressee Author Content 13.7 = = = = Dear Thomas, Thomas Elizabeth. enclosed is our invoice for June 2016. Actions Objects A successful grammar match gives you a parse tree of match objects (objects of Match type). This tree recapitulates all the individual submatches that contributed to the overall match, so it can quickly become very large and complicated. The deeper that match tree gets, and the more branches in the grammar there are, the harder it becomes to navigate the match tree to get the information you are actually interested in. To avoid the need for diving deep into a match tree, you can supply an actions object. After each successful match of a named rule in your grammar, it tries to call a method with the same name as the grammar rule, giving it the newly created match object as a positional argument. If no such method exists, it is skipped. (Action methods are sometimes also called reduction methods.) If it exists, the action method is often used to construct an abstract syntax tree (AST), i.e., a data structure presumably simpler to explore and to use than the match object tree, or it can do any other thing deemed to be useful. In this somewhat simplistic example of a basic arithmetic calculator, the actions dont try to build a complete AST, but simply do the bulk of the calculation work between the various tokens matched by the grammar: 258 Chapter 13. Regexes and Grammars grammar ArithmGrammar { token TOP { \s* \s* \s* \s*} token operation { <[^*+/-]> } token num { \d+ | \d+\.\d+ | \.\d+ } } class ArithmActions { method TOP($/) { given $ { when '*' { $/.make([*] $/ )} when '+' { $/.make([+] $ )} when '/' { $/.make($ [0] / $ [1]) } when '-' { $/.make([-] $ ) } when '^' { $/.make($ [0] ** $ [1]) } } } } for ' 6*7 ', '46.2 -4.2', '28+ 14.0 ', '70 * .6 ', '126 /3', '6.4807407 ^ 2' -> $op { my $match = ArithmGrammar.parse($op, :actions(ArithmActions)); say "$match\t= ", $match.made; } This prints the following output: 6*7 46.2 -4.2 28+ 14.0 70 * .6 126 /3 6.4807407 ^ 2 = = = = = = 42 42 42 42 42 42.00000002063649 The aim of this example is not to describe how to implement a basic calculator (there are better ways to do that, well come back to that), but only to show how actions may be used in conjunction with a grammar. The grammar is quite simple and is looking for two decimal numbers separated by an infix arithmetic operator. If there is a match, $/ (or $ for short) will refer to an array containing the two numbers (and $/ will contain the arithmetic operator). The parse method is called with an actions: named argument, the ArithmActions class, which tells Raku which actions object to use with the grammar. In this example, we dont really pass an action object, but simply the name of the actions class (actually a type object), because there is no need to instantiate an object. In other cases, for example if there was a need to initialize or somehow use some object attributes, we would need to pass an actual object that would have to be constructed beforehand. Whenever the TOP rule succeeds, the TOP method of class ArithmActions is invoked with the match object for the current rule as the argument. This method calls the make method on the match object, implicitly populates the AST, and returns the result of the actual arithmetic operation between the two numbers. Then, the made method in the caller code (within the for loop) returns that result that was set by make. 13.8. A grammar for Parsing JSON 13.8 259 A grammar for Parsing JSON JSON (JavaScript Object Notation) is an open-standard format for text data derived from the object notation in the JavaScript programming language. It has become one of the commonly used standards for serializing data structures, which makes it possible, for example, to exchange them between different platforms and different programming languages, to send them over a network, and to store them permanently in files on disks. 13.8.1 The JSON Format The JSON format is quite simple and is composed of two types of structural entities: Objects or unordered lists of name-value pairs (basically corresponding to hashes in Raku); Arrays, or ordered lists of values. Values can be either (recursively) objects or arrays as defined just above, or basic data types, which are: strings, numbers, Boolean (true or false), and null (empty value or undefined value). A string is a sequence of Unicode characters between quotation marks, and numbers are signed decimal numbers that may contain a fractional part and may use exponential E notation. 13.8.2 Our JSON Sample To illustrate the format description above and for the purpose of our tests, we will use an example borrowed from the Wikipedia article on JSON (https://en.wikipedia.org/ wiki/JSON), which is a possible JSON description of a person: { "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" }, 260 Chapter 13. Regexes and Grammars { } "type": "mobile", "number": "123 456-7890" } ], "children": [], "spouse": null, "Bank-account": { "credit": 2342.25 Compared to the Wikipedia example, weve added a Bank-account object to provide the possibility of testing JSON noninteger numbers. 13.8.3 Writing the JSON Grammar Step by Step Lets take each of the JSON entities in turn and handle them with rules. 13.8.3.1 Numbers The example JSON document above only has integers and decimal numbers, but we need to be able to recognize numbers such as 17, -138.27, 1.2e-3, .35, etc. We can use the following token to do so: token number { [\+|\-]? [ \d+ [ \. \d+ ]? ] | [ \. \d+ ] [ <[eE]> [\+|\-]? \d+ } 13.8.3.2 # optional sign # integer part and optional fractional part # or only a fractional part ]? # optional exponent JSON Strings There are many possible patterns to define a string. For our sample JSON document, the following rule will be sufficient: token string { \" <[ \w \s \- ' ]>+ \" } This will match a double-quoted sequence of alphanumeric characters, spaces, dashes, and apostrophes. For a real JSON parser, a rule using a negative character class excluding anything that cannot belong to a string might be better, for example: token string { \" <-[\n " \t]>* \" } 13.8. A grammar for Parsing JSON 261 i.e., a double-quoted sequence of any characters other than double quotes, newlines, and tabulations. You might want to study the JSON standards2 to figure out exactly what is accepted or forbidden in a JSON string. For our purposes, the first rule above will be sufficient. 13.8.3.3 JSON Objects JSON objects are lists of key-value pairs. Lists are delimited by curly braces and pairs separated by commas. A key-value pair is a string followed by a colon, followed by a value (to be defined later). This can be defined as follows: rule object rule pairlist rule pair { '{' '}' } { [ [',' ]*] } { ':' } We can use a regex feature that we havent seen yet, the quantifier modifier, to simplify the pairlist rule. To more easily match things like comma-separated values, you can tack on a % modifier to any of the regular quantifiers to specify a separator that must occur between each of the matches. So, for example /a+ % ','/ will match a or a,a, or a,a,a, etc. Thus, the pairlist rule can be rewritten as follows: rule pairlist { + % \,} rule pairlist { * % \,} or: if we accept that a pairlist may also be empty. 13.8.3.4 JSON Arrays Arrays are comma-separated lists of values between square brackets: rule array { '[' ']'} rule valueList { * % \, } Here, we again used the modified quantifier shown just above. 13.8.3.5 JSON Values Values are objects, arrays, string, numbers, Booleans (true or false), or null: token value { |