nd the safety of our citizens in a turbulent world. Where the evil of terrorism, sadly, is unpredictable and the capacity of rogue dictators and rogue states to develop a nuclear capability is unquantifiable. That obligation to me is fundamental. I think that being in NATO is part of that defence capability and there is an interesting dichotomy here. The SNP appears to support being in NATO, which is a nuclear organisation. Mr Wilson, very frankly, had a different analysis. I disagree with him, but at least there was a candor about his analysis. I am listening with interest and the member has referred to rogue states. I wonder if she can give any example of any rogue individual or rogue state who has been deterred by any country on earth holding a nuclear weapon. I think that there is a very powerful argument, Mr Stevenson, that huge international influence from nuclear powers was brought on to Iran. We now see that Iran has agreed, thank goodness, to reign in its ambitions in that respect. However, that takes me to the very point of my argument, Deputy Presiding Officer, that the position of defence strength enables us to do something else that does make possible continuing and constructive discussions about multilateral nuclear disarmament. That is a process that has commenced. It is continuing, and it is one to which the major nuclear powers are contributing. In the present situation, with threats that we do not know about, I feel to embark on unilateral nuclear disarmament would be a breach of obligation by government, state and citizens. My colleague John Lamont spoke eloquently about the nature of deterrent, because that is what we are talking about here. It was surprising, because when Christina McKelvie was challenged on the concept of deterrent, she declined to even respond to that challenge and did not address the point. Apart from the Scottish Government motion presenting a false choice, it is glaringly incomplete in a manner that any observer would find disquieting. There are those who deplore nuclear weapons, want rid of them, but they are honest enough to accept that removal of trident from fast lane does not make Scotland a safer place, does not make the United Kingdom a safer place and does not make the world a safer place. Those people who hold that view are honest enough to argue that unilateral removal is not, in itself, the way to deal with it. Those people are honest enough to concede that simply getting rid of nuclear weapons from Scotland makes no meaningful contribution to the wider debate of multilateral nuclear disarmament. The motion is also very disappointing. Apart from not encouraging either constructive or reflective debate, it does not even pause, as some have observed, to reflect on the actual consequence for fast lane and the western Bartonshire economy of losing that base for our nuclear submarines. I want to make progress, Mr Mackay. No thought has been given to the thousands of skilled workers who lose their jobs with no comparable alternative. I represent that area. I live in the real world. I know that there is a real biting human and economic cost to losing that nuclear capability and those nuclear submarines. Clare Baker at least acknowledged that. Her solution to me is not credible, but at least she accepts that there is a problem, as did Neil Findlay and Sarah Boyack. One thing can be said of the Scottish Government's position, it is clear—I disagree with it—but it is clear. The same cannot be said of the Labour party. Now, in the astonishing position, it has a Labour leader who does believe in Trident, but her party in Scotland does not. Her UK leader does not believe in Trident, but his party does. However, the overall message from both the SNP and Labour is the same. They will hike up taxis and they will scupper out the country's defences. To any workers in the defence industry in Scotland, there is a clear message, only the Conservatives will keep your taxes low and your defence jobs safe. We will fight for you in the real world and keep your country secure. That has been, in many respects, an interesting debate. I support my colleague John Lamont of Enlunch. Thank you, Presiding Officer. I agree that this has been, by and large, a very good debate and, hopefully, reflects the type of politics, the kinder politics that we can have in Scotland where we can debate big issues in a way that is constructive. In terms of the amendments in the motion, I can say that, in terms of John Wilson's amendment, the position of the Labour party in Scotland is that we do support being a NATO and therefore we would not be able to support that amendment. In terms of the Conservative amendment, we would not support that, but, interestingly, the Conservative amendment asks the Scottish Labour Party to decide what is the position on the future of the UK's nuclear deterrent. I would say to them that the Scottish Labour Party, at its conference at the weekend, over 70 per cent of the delegates and the affiliates voted to support a position, which is that we would not renew Trident, so our position is quite clear. In terms of the motion to our amendment, I would want to thank and congratulate the Government for agreeing to support the Labour amendment. I do hope that, in this area, it is an area where we can work together to make the arguments and make the case as to why it is not in Scotland's interests, it is not in the United Kingdom's interests and it is not indeed in the world's interests for the UK to renew its Trident weapons. I have, certainly, most of my adult life supported multilateral disarmament and believe that it is important that we do negotiate and there have been successes there. However, when it comes to the point of the renewal of Trident, I think that it is legitimate that, at that point, you would pause and you would have a look and you would ask the question, is it right that some 30 years on for the last decision on this, is it right to renew it? As Claire Baker pointed out, the world now is a very different place and the threat in that world is very different. The threat to us is a country to Scotland but it is also part of the isles to the United Kingdom. The threat is much different and, therefore, it is legitimate that, at that point, you would ask yourself, should we spend between 100 and 160 odd billion pounds on replacing the Trident nuclear weapon? I thought the contribution by Malcolm Chisholm. He highlighted very clearly that that case has not been made and I will come back to that. Trident is an expensive status symbol that has no military value and drains resources from conventional defences and socially useful investment. Dick Brody reminded us that Malcolm Chisholm had quoted Tony Blair, who said that it was more about a status and that it was about having a seat at the top table. I would have to say, Presiding Officer, that it is a fairly expensive seat at the top table, if that is all that is. Does the member share our bewilderment at the Conservatives that are quite happy to cap families who have too many children but not cap the cost of a moral and totally useless weapons or mass destruction? I think that that is the point. If it was proven beyond doubt that having a nuclear deterrent was absolutely necessary, indeed, if it was proven that we needed a nuclear deterrent for the safeguard of this country and the peoples of this country, we would not be arguing over the cost. The fact is that all the evidence suggests that it is not in our best interest to have a nuclear deterrent. Nuclear weapons have no military rationale. They are neither a deterrent nor a defence to the very real security threats that faces our nation. To answer the Conservative question, if I could quote here from the former Secretary of State for Defence, Michael Portillo, who served in John Major's Government until 1995-97, so he knows a wee bit about those things, Mr Portillo said earlier this year that our independent nuclear deterrent is not independent and does not constitute a deterrent against anybody that we regard as an enemy. It is a waste of money and it is a diversion of funds that might otherwise be spent on perfectly useful and usable weapons and troops, but some people have not caught up with their reality. It would suggest that the Conservative Party has not caught up with that reality. Christine Grahame Can I press the member to go even further and say whether he considers in any event the use of such a weapon of mass destruction is immoral, that there is immoral argument against not holding them as well as the deterrence as well as the cost? Alex Rowley I certainly think that there is a strong moral argument against investment and tried and the use of tried and the leader of the UK Labour Party has said that if he was Prime Minister he would not press that button. The case in terms of the moral argument against tried and I think has been made but the striking thing for me in looking at this debate is the lack of debate that has taken place right across civic Scotland, right across civic UK and therefore hopefully the discussions on this issue that have been there over the weekend, hopefully the discussions and if this Parliament passes the amended motion today, then hopefully we will start to generate a wider discussion across the United Kingdom so that people will examine the arguments that are being made because at the end of the day if you examine the arguments I think you would think twice. We have had a number of speakers that have talked about polls but I would want and saying that these polls would support the renewal of tried and I think when people actually look at the arguments Malcolm Chisholm talked about a big tent where he quoted the late Dennis Healy but also generals, military people, the military leadership are at best neutral on this issue. I think once you start to present the facts and that's what we have to do in terms of that but it does leave us, it does leave us with a real issue and a real concern and that's what Labour is focused on here in Scotland because we accept that there are people who are working in jobs that are dependent on tried and that's why I would commend the report from the STUC the case for a Scottish defence diversification agency. Now there are those who simply dismiss this as pie in the sky but this report actually shows that where this has been done properly and done right and they do point out not to if you're looking for a bad example of defence diversification then look no further than the UK defence diversification agency so there are bad examples but there are examples right across the world that would be important for us to look at in terms of diversification of jobs. I think it's also important that Malcolm Chisholm talked about this where he said, the job consequences of keeping tried and the threat to conventional defence investment so I think it's important also that people don't raise scare stories for places like Recythe and Monkinstitue and we're actually I would say tried and is a bigger threat to jobs there and we should be investing in the conventional forces that are there. We were also keen, Presiding Officer, not to not to start trying to identify lots of areas that you could spend this money in. As our leader at a UK level has said, it's important firstly that we look at the defence sector, look at investment there, look at diversification, look at protecting jobs but I certainly welcome this debate today. I think we need to move forward, we now need to make the case across the rest of the United Kingdom because if you look at the evidence, the evidence points clearly to not renewing the tried and nuclear weapons system. Many thanks and I now call on Keith Brown to wind up the debate. Thank you Presiding Officer. I think it has been as both Alec Rowley and Annabelle Goldie have said an interesting debate and I think it's potentially a very significant debate. In fact, potentially an even more significant vote shortly. One or two Labour members with some justifications spoke of their pride in their party's debate and the decision that they took to oppose tried at their conference and I accept that statement of pride. I would hope that they in turn would accept my pride in my party's steadfast, long-term opposition to not just tried in replacement but tried in itself and also to polaris. We had a number of compelling arguments against nuclear weapons from various people, Christian Allard, Christina McKelvie, Kevin Stewart, Jean Urquhart, John Wilson and many others, Chick Brody and two that stood out from me. I think Malcolm Chisholm did make a very good speech in terms of trying to lead out how it's possible to build support for the position of not renewing tried and pointed to the fact that perhaps a strategic and military argument should be more likely to work in terms of some of those specific, specifically on the conservative side who would otherwise not want to oppose renewal. I think that that was a very important point. We can see how that tent is open to many other people, perhaps less so for some of the Conservatives, but when you look at some of the very compelling arguments against the strategic and military justification for tried and I think it is still possible to do that. I wish I could say that we had a compelling argument for tried and renewal but I just don't think that we did today. Jim Hume left me very confused. He said that he was for a minimum deterrent and then described that minimum deterrent is zero. If that means—and I'm genuinely not sure if it does mean this—that Jim Hume means that the Liberal Democrats' position is that they would not have nuclear weapons then welcome to the big tent. I wasn't sure exactly what he was saying if it was a smaller number of nuclear warheads but he did say zero so I would have assumed that he's now on board, which is good news. I would just mention Jackie Baillie's speech because it really was nothing much more than an anti-SNP rant. It didn't do her or our arguments any credit whatsoever. The only people she'll get any credit from were the Tories who applauded it wildly. I think it's also not possible to say that although I do agree with Malcolm Chisholm, you have to try and build support. I can't see us having more success at least with the Scottish Conservatives. There does not seem to be that diversity of opinion within the Scottish Conservatives that there was within the wider Conservatives across the UK. We've heard about Michael Portillo's statements. We've heard about Crispin Blunt. There are many other examples, including his human military personnel, but today we've got a new doctrine, a new defence doctrine from the Tories, which was that it doesn't really matter what the price of the nuclear weapons is. We'll buy them anyway. I'm not even asking for the price. That was the point that John Lamont made when I think that he was questioned by Derek Mackay. At what price would you say that it's too expensive to have nuclear weapons? There was no price. It does not matter what the price of nuclear weapons is to the Tories. They want them anyway. I'll give rate to Alex Johnson. I'm keen to understand the intricacies of the SNP position over this. I remember that 20 years ago, when the decision was made to give the Trident submarine maintenance contract to Davenport instead of Recife, the SNP described that as a betrayal. They described it as one of the reasons why Scotland should consider independence. How has your position managed to change radically in that sense? I think that Alex Johnson may be aware of one or two changes that have happened over the past 20 years. However, I think that our position is pretty clear if you look at the motion that we have put up. Perhaps if he had started off with that, he wouldn't have to ask questions about our position. We have also heard today about the billions that Trident nuclear weapons have cost to taxpayers and about the untold billions still to come. Should the UK Government continue with their plans to construct and put into service another generation of submarines carrying Trident ballistic missiles, we have heard how spending on the successor Trident system would put conventional defence equipment programmes under pressure, with no clear threat that justifies a possessive nuclear weapons. Patricia Ferguson, I thought, made a very good speech, but she mentioned a number of very senior military personnel who are against nuclear weapons for the very good reason that it squeezes out funding for other conventional defence, including shipbuilding, which was mentioned by one or two others. Although I am keen to take on board the views of senior military personnel, I am also quite interested in your average soldier, infantry soldier, sailor and air force personnel, not at a senior level, who absolutely are sick to the back teeth or have been cheated out of the proper defence equipment, whether it is boots or helicopters because of spending on something like this. It is not just the senior military personnel. I can tell you from my own experience that it is not just senior military personnel who have no time for nuclear weapons and the huge extravagance that they represent. Members have also spoken passionately about the UK Government's prioritisation of welfare cuts, which even the unelected House of Lords has questioned. If the Tories would go as far with George Osborne to try and squeeze through renewal of trident with a statutory motion to the House of Commons, there is no reason why they should not be opening us up to much wider debate. I will come on to this later on, but we have now seen huge support across this chamber to oppose the renewal of trident weapons. I hope that when there is a debate on this, it will be a proper reasonable debate carried out in the House of Commons. Most important, we have heard again about the devastating and indiscriminate effect of nuclear weapons. I think that we all have said that even a very small nuclear exchange, and I use that phrase advisedly, would have catastrophic humanitarian, environmental and economic consequences. For how much longer do we want to continue with the risk that one day, one of those weapons may once again be used, whether by accident or by design? As I said, we have had quite a substantial debate about the job implications of those issues. Recently, during a member's debate on spending at HMNB Clyde, the Scottish Government welcomes investment in fazlain as a conventional naval base, as we welcome investment in conventional equipment facilities and arrangements to support our defence personnel, families and veterans, wherever they are based. We also play our full part in the firm base arrangements in shooting at both military and civil society in Scotland that they are working together to care for and support our service community. Our disagreement is not with those that serve in the military, whether at home or elsewhere. We would again call on the UK Government to explore how HMNB Clyde could be reconfigured for wholly conventional naval use. I would also note with particular interest the findings of the STUC and Scottish CND, which found that a detailed breakdown of the skills involved in trident-related work showed that many of those skills could be transferred to other non-trident submarine surface warship work or alternative economic development. However, it is indefensible for the UK Government to consider spending, just to mention the price again, the latest price that is £167 billion, of whatever the final figure actually is, on the renewal of unwanted nuclear weapons. I thank the cabinet secretary very much for taking that intervention. On the topic of £167 billion, does the cabinet secretary agree with me that the UK Government should at last take responsibility for the nuclear veterans exposed to radiation on Christmas Island once and for all before they die? The member makes a very important point, which has been debated, I think, with some credit in this Parliament on a number of occasions. We are aware that it is a legal case on-going, but that is part of the legacy of the development of nuclear weapons of the UK and it should stand up to its responsibilities. To conclude, Presiding Officer, I think that today has been a very significant debate. You have three minutes. For the first time, we will see the awful— I am very grateful to the minister for taking an intervention. Will the minister consider setting out a timetable for Scottish Government work on the whole issue of defence diversification and the key suggestion in our amendment about defence diversification agency being set up in Scotland to focus not just on Trident, but on some of the other transferable skills that I know that he welcomes that he mentioned in his speech, which we are very much welcome. I would say that the Labour amendment mentions diversification in the event of cancellation of Trident, but if the member suggests that we should think about that beforehand, I am more than happy to do that. I would make the offer for, I am not sure if it is Claire Baker, but whoever it is within the Labour Party. In fact, any of the parties in the Parliament who are against Trident, I want to discuss both how we can campaign, because this should not be the end of the discussion on this, but also how we look at the issue of jobs in relation to an eventual cancellation of Trident. I am more than happy to involve the other parties in doing that. I would be happy to do that. That is the reason why it has been an important debate, because, if you look at the decision that it may be taken very quickly, that is going to be a huge decision that will last for perhaps 60 years. However, we have a situation now where, if the voting goes as we expect it might go, we are going to have something like two thirds of this chamber saying, do not renew Trident. We are going to have 57 perhaps out of 59 of Scotland's MPs saying, do not renew Trident. Where is Trident going to be if it is renewed? It is going to be in Scotland. It is an extremely powerful message that we send out today. If we all support, or most of us support, the request of the UK Government that does not renew Trident, it is a hugely important decision. It cannot be the last thing that we say. That could be taken very quickly. We have to move from this decision today, the agreed position that we have, certainly with the two largest parties in the Parliament and with some of the smaller parties as well. To take this further, we cannot let the UK Government take a decision on this without letting them know exactly what Scotland thinks about this decision. It is not just the parties, it is not just the MPs, it is the churches, the STUC and the majority of Scottish MPs, as I have mentioned, but many people throughout Scotland would be appalled by the decision to renew these nuclear weapons. I am delighted that we have managed to reach some kind of agreement on this after many years of being at odds. I hope that we go from this today to take this forward to the UK Government and make sure that we never again renew Trident weapons of mass destruction. Thank you. That concludes the debate on Trident welfare and warfrying. We now move to the next item of business, which is decision time. There are four questions to be put as a result of today's business. The first question is at amendment 14681.3, in the name of Clare Baker, which seeks to amend motion 14681. In the name of Keith Brown, on Trident welfare or warfare, be agreed to, are we all agreed? Parliament is not agreed. We move to vote. Members should cast votes now. The result of the vote on amendment 14681.3, in the name of Clare Baker, is as follows. Yes, 96, no, 17. There were no abstentions. The amendment is therefore agreed to. Can I remind members that in relation to today's debate, if the amendment in the name of John Lamont is agreed, the amendment in the name of John Wilson falls? The next question then is amendment 14681.1, in the name of John Lamont, which seeks to amend motion 14681. In the name of Keith Brown, on Trident welfare or warfare, be agreed to, are we all agreed? Parliament is not agreed. We move to vote. Members should cast votes now. The result of the vote on amendment 14681.1, in the name of John Lamont, is as follows. Yes, 12, no, 101. There were no abstentions. The amendment is therefore not agreed to. The next question is amendment 14681.2, in the name of John Wilson, which seeks to amend motion 14681. In the name of Keith Brown, on Trident welfare or warfare, be agreed to, are we all agreed? Parliament is not agreed. We move to vote. Members should cast votes now. The result of the vote on amendment 14681.2, in the name of John Wilson, is as follows. Yes, five, no, 108. There were no abstentions. The amendment is therefore not agreed to. The next question is motion 14681. In the name of Keith Brown, as amended, on Trident welfare or warfare, be agreed to, are we all agreed? Parliament is not agreed. We move to vote. Members should cast their votes now. The result of the vote on motion 14681, in the name of Keith Brown, as amended, is as follows. Yes, 96, no, 17. There were no abstentions. The motion, as amended, is therefore agreed to. That concludes decision time. We now move to members' business. Members should leave the chamber, should do so quickly and quietly.


Thought I'd take up the opportunity today to Watch the original Vitamix infomercial with you. I've seen parts of it They play it on a loop like the first two and a half minutes at Vitamix headquarters It's infamous. It's legendary and it's It's aged. I mean it's from 1950 It was the first like like they say it was the first infomercial ever a TV was so rare It was cheap to get TV time So Papa Bernard went on TV to sell the Vitamix machine. He had been pitching products at fairs and festivals and on the streets for years and he This was the first time he had used this medium. I thought it'd be fun to watch together the whole thing We're gonna press play I'm not gonna stop it pressing play now.  You'll lose your income and you'll lose your life Now ladies and gentlemen right away.  I'm going to call your attention to the machine here the mechanical part of it The Vitamix remember the name Vitamix we have a motor that travels at the rate of 8,000 revolutions a minute on a low 14,000 revolutions a minute on high You get a one-year guarantee on this motor if anything goes wrong with it in one whole year The company will repair or replace it free of charge Now I'm going to Now it's seven for ten and that is this stainless steel bowl Everyone loves the stainless steel The finest material in the world for the preparation of food the same material is used by the United States government on all the battleships and in the hospitals for the preparation of food stainless steel on the inside of a container of four little blades That are made of stainless steel they travel at the rating thousand revolutions a minute now ladies and gentlemen there I'm going to first before I put in this carrot There's a notch here and a notch over here you set that too so they match Before I put in this carrot easier.   We're going to use the glass bowl And you will look at every operation. Now I turn on the machine to low and then to high and there's your breadcrumbs already made By electricity Now I'm going to show you how you can grind your wheat many of you would like to make your own whole wheat and for cereal possibly or for muffins or for Bread and do your own baking at home. It's hard to buy a whole wheat in on the market So you can get your whole the grain the whole wheat grain and put it in this machine Turn on the machine to low and then to high and you'll grind your wheat into a cereal in about one minute time It takes two minutes to make whole wheat flour If you want corn meal you can put the grain the whole grain of corn in that and you'll have your corn meal in one minute time and you'll have the flour corn flour in two minutes time you people who are on a diet Maybe you can't tolerate You can put in the soy bean and make your soy bean flour barley flour rice flour now. We have our cereal here you put this in a double boiler and It will cook in about 20 minutes and you get all the brand the middling the germ and the laxative of the whole box it is now ladies and gentlemen Before I put in this carrot, I'm going to put in just a little liquid our recipe book of 500 recipes tells you What liquid to use and how much to use in every one of the recipes? We tell you how to make pie fillers omelets cake batters how to whip your cream turn your butter how to make Your soups your waffle batters your potato pancake batters, you know, I saw a fellow the other day He said he had had a machine rather that he had been married for 30 years And he'd never had a potato pancake in 30 years now think of that like 30 long cold winters and no potato pancake Say we give you a recipe here that tells you how to make the finest potato pancake But was ever made by any woman that has given me by a good German cook up in Milwaukee And I'm going to pass it on to you now ladies and gentlemen Before I put in the carrot, I'm going to add just a little Water with a little orange juice in it the recipe on page nine Calls us they help the Vitamix health cocktail now before I put in the carrot I have a patriotic duty to perform I happen to be the president the natural food gentitude as you know and we are trying to teach some others of America Exactly what the Red Cross and the parent teachers Association are trying to put over drinking games Must mother one shot two no no of your family a sip Is going blind? Do you know right now in America that one half of us children at all are looking through a pane of glass? Do you know right now in America that half of America 27 year of age and Over hasn't got a tooth in their mouth Call up your dentist you say yes, you can come over seven weeks from next Friday There's so many ahead of you. Do you know that one-third of the American children claw weird of age? Haven't got a tonsil in their throat and We had a million boys go before the draft board in our last World War and 460,000 of them were rejected think of it Bring it here General Louis B. Hershey says it's a national disgrace that 90% of those boys Because of malnutrition in other words at the dining room table drink drink drink I'll show you why those conditions exist You know, there's almost one half the American women who can't nurse their baby They have to ask a doctor if they can nurse their baby There isn't another living animal that has to ask such a question But the mother is not feeding herself right in order to make the right of the milk and the quality He's got a good point there So the doctor says give it orange juice cod liver oil purees of edgables and she does Preaches the kid gets old enough to come to the table then when the doctor isn't looking she says to that little child You don't need minerals and vitamins anymore So she throws the whole works out the winter and the first meal she gives that child is one of the most Dmineralized Devitalized food she can possibly give him which is mashed potatoes think of it half of America living on mashed potatoes today You come to my house mashed potatoes. I go to your house mashed potatoes. We go over to the restaurant The hotel the cafeteria mashed potatoes one lady.  She dodges it out and throws it in the garbage can and then she takes a prayer It takes the knife and she cuts the potato half and two put it in a pot of water and for 25 minutes Now she does give it the work. She boils out every mineral And after she gets them all boiled out what does she do with them why she trots right over to the kitchen sink Oh my god and grains the whole works down the sewer.   Did you ever try to feed a horse cook carrots? That's an amazing point But mama has a cookbook and on page 262 it says buttered carrots. It says slice and dice So she takes that blessed carrot and she slices and she dices it says to 35 minutes She turns up the gas. She boils out the iodine calcium phosphorus iron silicon sulfur potassium and magnesium A lot of blaming mama here and then she trot to the kitchen sink and drains them down the sewer Down the drain goes the vitamin a that builds resistance against all infectious diseases Down the drain goes the vitamin a that builds the eyes if I was doing this today I would make the same point with juice like juicing traditional cold press juicing Everything just goes in the garbage except for the sugar basically they get a set of clackers Papa and mama's teeth are in a water glass every night down the sewer goes the iodine in the built a thyroid gland Out with the kids tonsils before the 12 year today with the table loading down of mashed potatoes and buttered carrots and Slice and mushroom gush Papa has to sit at the head of the table and thank God for the food that mother threw down the sewer Oh Get a vitamin machine my dear people get a vitamin machine Quit kidding your family mother and see that those minerals and vitamins go where they belong into the bloodstream and Build eyes and teeth and tonsils and nerves and health so we put in a little pineapple juice a while ago And we're going to turn on the machine on the low and then the hot And we're going to cut in this carrot and we'll drink that carrot just exactly like molded milk Putting into the bloodstream Instead of the kitchen sink every mineral and every vitamin the next thing I'm putting in Ladies and gentlemen is one of the finest sources of calcium The old hand eats the wheat on the corn He takes from the grain a natural calcium and secretes it and forms the shell of that egg Okay, it has been pre-adjusted by the hand and if you can break it up sufficiently You have the finest source of calcium for expectant mothers nursing mother bone trouble to trouble There's a doctor in Iowa who's made thousands of yes hundred to thousand the pound of powdered eggshells for his Oh, no, so we're going to practice it and we'll throw in the protein. Okay, but we'll also throw in the We did it just exactly like more than now The next one I'm putting in is a finer sugar Here's your sugar that every person in America should have every day a sugar that's loaded with iron and calcium and magnesium phosphorus of blood cells Loaded with iron and calcium It's a sugar that was in the Garden of Eden made by God Almighty and when you make these cocktails for your children So that they can take them to school mother Hey, when you put them in the thermos bottle you'll be sure that they're sweetened with raisins And you'll be building red blood for their eyes and their teeth I can't knock it. Our website's life is no yoke. It all started with egg whites No table to set no dishes to watch think of that say all you need is a water glass for each member of the family So I'm going to put in a wonderful protein the monkeys beefsteak peanuts I'm going to put in ladies and gentlemen The finest fruit When he placed in our soil the almost to grow the old apple tree That old tree goes down in the soil of old Ohio up, California. There's a preacher Pastor I hope he doesn't put the whole thing in You shouldn't put the core of an apple in the seeds are arsenic just And down to the stem and the God of heaven the great chemist of the universe Stores those eight minerals and four vitamins in the skin of the apple He places the pectin in the field he places the laxative in the field the hand of God He takes the paintbrush of all mother nature and for five months He labors building the most helpful fruit the most beautiful fruit painting every apple on that tree What a wonderful artist Oh, I love that With a very nice and she says God doesn't know how to make apple And in one minute in one minute that woman deliberately destroys Unmakes what God made.  She takes this 85% water put it in 100% water and For 20 minutes some cook and she puts on a lot of white granulated sugar and says have some apples Would you like some sugar with sugar Get a vitamin machine and when you want apple sauce Put in water cut the apple and two to see if there isn't any worms in it If you're a vegetarian you don't want the worms then you cut in the apple core Seeds and all doing a little honey or a little raw sugar put it on the table and serve it And if you want a laxity say Here's the way the animal gets their laxity turn your family out on the green pasture Put a little green spinach in the apple. Okay greens a finest laxity On earth a natural laxity now, ladies and gentlemen, we'll put in a wonderful Eurethic, it's the same as a watermelon looks like a watermelon grows on the same long bind It's up the same mineral has the same seeds and works on the kidneys exactly like a watermelon So if you want a natural Eurethic, so in the cucumber cucumber, you'll drink that cucumber I did not know that that it's related to the watermelon. Here's one of the finest vegetables one of the finest vegetables on earth for the nerve so far, there's I say women egg some pineapple juice Celery spinach Cucumber in the large every time they move a joint Cry out to the high heavens with arthritis Dr. Pope a great medical doctor in the Oral Walk laboratories There's a reason women have arthritis because they were taught from the little girls But they're made out of sugar and spice and everything nice how they love their white bread their toaster biscuits are pie They're cake they're jelly they're jam and all of those carbohydrates But dr. Pope says the excessive amount of carbohydrates gets in the bloodstream Settles in the joints he'll take them all away from if you have arthritis girls and he'll make you drink one pint of celery juice a day Which is 40% sodium to dissolve the inorganic substance in your joints and while I speak of celery You can make celery soup put in some milk so in the celery a little piece of onion one minute soups ready Take it over to the stove and warm it don't cook it 40 recipes in our recipe book for making soup here Ladies and gentlemen one of the finest fruits one of the finest fruits and say Your children if you want to give them all the milks and milkshakes, let them make them themselves Let them put some milk in the machine get a bite of it when their kitty neighbors come over Let them throw in the right bananas the right peaches the right big brocats Take your frozen strawberries and your frozen fruits and make your Wonderful drinks in here. Let the kid build his own teeth Here's the way that you cool off your drinks You can for instance if you want lemonade if you want lemonade put in some water and cut in the lemon Yes, you can use skin He's still using the same Demo and to cool it to talk about longer. There's still a full egg with shell in there now ladies and gentlemen You can also you people you people who have a well if you indulge What I mean if you must use alcoholic drinks here's the way you can do it I know a lot of you have seen this machine on the swanky cocktail bars of the country They're making frozen daiquiri's West Indies gin fizzes Tom Collins Mary Collins Katie Collins the whole Collins family Yes, you can make them in this machine But don't say here's to your health when you drink them all you do is to crack up your ice cubes and throw them in And you'll have your frozen drinks in just one minute time now ladies and gentlemen. It's true frozen like margaritas whatever are So much better made in the Vitamix Oh, I know none of you can drink this I wish that I could come into your home and give you a drink of it But I can't come into your home, but I'm gonna pour this off now in just a minute That's the challenge the consistency of the video demos That's the gap we gotta try it once you try you're hooked get that we tell you how to make pipe fillers Omelettes cake batters how to whip your cream I'm going to show you in a little bit how to turn your butter And I'm going to give you show you how to make several other things now turn this machine off right now And we're going to pour this off and I want you to notice ladies and gentlemen I pour this as I pour this That there isn't any seed no pulp No eggshell It is all completely liquified. Please drink it ready to go into your bloodstream and build eyes build teeth Build top. I like that build nerves Build health nerves and when we build health We will be the richest family in this world.  You have your income and you'll live to be a ripe old age. That's right. I Wish that I could give a sample of this cocktail to every one of you people in this audience. I feel your man It's impossible So I'm going to pour a little of it out in this glass I'm going to sample it myself. He looks thrilled. I'm going to say Here's to your health delicious Perfect health to every one of them My dear people the school nurse When she comes to your school and that little girl has her thermos bottle full of a drink like this The school nurse is going to send the report back to mother and father You're feeding your little one scientifically and you people who are working in offices and factories That's the most bottle could take a Painter of quarter of it to work with you. That's right And you'll have the most perfect meal you ever had in your life knowing you're getting everything that your body needs 500 recipes in this book. Where can I get one? That's what you're thinking about. What will it cost me? I'm going to show you in just a minute tell you where to get one And I'm going to tell you how you can get one Absolutely free.  Will you do that, please right now? Get a pencil on a piece of paper because we're going to flash on the screen in just a minute. Do you want a Vitamix either way? The telephone number of where you can get your machine the price of the machine With a stainless steel bowl. Oh, I know what it's gonna do. 500 recipes We're going to give you a one-year guarantee If anything goes wrong with this machine in one whole year The company is going to repair or replace it for your child. He's gonna say it's gonna pay for itself I'm going to give you one of the most valuable charts That you could have in your home What right has anyone to buy food and spend their harder and money and then boil it and drain it down the sewer and Throw away the elements that build a healthy body This little chart tells you the minerals and vitamins of every food that you eat 250 of them and it tells you the amount of minerals and vitamins in each one of those foods and even counts your calories I want to show you how it works. If you'll permit me. I'm going to bring an enlarged Wheel of Life chart. Oh, no into this picture. Oh, no around the outer edge. We have our vegetables Yes, every vegetable that you should could buy in your market Oh my god have all your cereals the wheat the rice the milk the corn we have here every fruit That is in the kingdom. We have nut meats. We have seafoods. We have all your meats I don't like the dairy products such as butter cheese eggs and so forth milk We have here miscellaneous beer chocolate coffee honey molasses seaweed tea To tell you what they mineral and vitamin content is of each of them All you have to do is to point this arrow to the food you want to analyze suppose somebody in your home needs a lot of vitamin A just turn to the vegetables here until you see the ones that are rich in vitamin A Where's the vegetable right here? This is such a clever gimmick like people love too much information And analyzing what they need what they think they need Vitamin abundance of vitamin A large amount of vitamin B. The Vitamix app is a modern-day version of this It's gonna tell you every vitamin and mineral and calories and nutrition facts and protein Sulfur and silicon that's the way you analyze every food up here your your calories It tells you how many calories in every one of the foods at Judy this ladies and gentlemen sells for one dollar It's worth fifty dollars to any home that has health As a paramount issue now ladies and gentlemen, you're gonna get that free if you order here tonight And ladies and gentlemen, I Have a special offer for you This machine with a stainless steel bowl Usually sold for five dollars more than the glass bowl I said we's gonna give you the stainless steel bowl machine for the same price As the glass bowl 34 95 that's for a Vitamix Every person who orders the machine right now Right now You're going to have flashed on the screen in just a minute Where to get it the telephone number and how to get it get your pencil and paper ready Every person who orders a machine right now offer this broadcast right now I'm going to see that you get the stainless steel bowl with our new Bakelight handle you can use it just as a pitcher you can pour off your mixtures Suppose you're making hot cranberry sauce And you'd pour the hot mixture in here and you'd have to take a hold of either the glass or the stainless steel jar I'm poor as you saw me doing a minute ago.  You might even drop the jar so now This jar that I'm going to give you as the bake light handle and you use it just as you would a water pitcher pour it off Into your container your orange. It's such a good my man.  It's almost 400 bucks It'll come to your mailbox partial post prepaid for only $34 and 95 cents and remember You can take the cream off the top of your milk and pour it in here And you'll get a quarter of a pound off the top of two quart bottles of whole milk a quarter of a pound of butter And it's 65 cents a pound you'll pay for your machine in the butter You save in just a few weeks time Is that how it's for you? You can't afford to go another day without a vitamin machine. Go get it. Get a vitamin machine right now It's going to be flashed on the screen immediately.  I love it. It's the same pitch It can do a million things delivered to your door Wow, I'm glad I watched that now. I want to recreate that. I want to do that. I want to do a 24-minute Demo throw a bunch of stuff in there and do a lot of pointing and say you can't afford to Spend another day and not have a vitamin mix and and do impressions of a crazy mom who doesn't know nutrition and Really use fear to sell these things Dude was good at it. I love that. He was wearing suit in the kitchen If you haven't subscribed to our channel already do that hit the bell to get notified and We'll see you the next one guys


do arithmetic with church numerals in Ruby. This is not what I'm going to be talking about, though it is pretty cool. Does my clicker work? Yes. Also, functional programming in a non-functional programming language is a myth. So you can basically skip this talk. If you want to already cut straight to the cocktails, that's absolutely fine. I'll wait a minute for people to leave if they want to. Also, if you are a professional hater, you're welcome to leave. If you see this man later at the bar and he's just complaining about every talk, if you see him complaining about my talk or any talk, just kind of nod and give him a beer. Love you, Tamash. This is me and Hedias Charlie from JRuby singing karaoke in Taiwan. This was RubyConf Taiwan this year. I was going to say, like public service announcement, we're going to do another Ruby karaoke tonight. Charles intensely and I have been pulling this meme, but I made a few phone calls and apparently the one karaoke plays in Gent closed. So the closest would be Antwerp. I guess that's not what's going to happen tonight. But we can still sing songs on the boat. Unfortunately, this is me and Charles singing a whole new world. The song you just heard. I was his jasmine. He was my Aladdin. Also, public service announcement, Ruby standard lib, the Twitter account, take submissions. I know it hasn't been too active. I'm very sorry if you have cool stuff in Ruby core, in Ruby standard lib that you want to show off. Tweet at me, tweet at Ruby standard lib, should be an email. I'll put it up there. Right. So now to the main topic of this talk, functional programming for Rubyists. This is me. I'm Arne Brasseur or Plexus on GitHub and Twitter. I'm originally from Belgium. I actually lived in Gent for five years. It is by far my favorite place in Belgium. Such a beautiful and lovely city. But then with a detour of two years in China and Taiwan, I ended up in Berlin, which is my current base. I'm almost really, really happy to be here. No, not yesterday. Two days ago, Wednesday, the day before our camp, for the second year in a row, we organized Ruby lambic. So there's a style of beer lambic and then from lambic they make creak and hues. These are unique type of beers that you really only get in and around Brussels. There's a long story about it.  We visited a brewery in the morning in Brussels. And then in the afternoon, we went and visited some really old bars. And so this bar in particular is 300 years old. It's been in the family of this guy who's 93 years old who's still running the bar.  And so, yeah, we were very happy to be able to be his guests.  So, I mean, quite likely we'll do another next year. So keep an eye out for that. We're still kind of debating the exact formula this time around. But that was a lot of fun. I really wanted my good friend Piot who you saw yesterday talking about week grab and other standard lip stuff to join us. But as it turns out, Piot actually prefers Radler over beer for Belgians or other people who aren't really familiar with German beer culture. Radler is basically beer with lemonade. But luckily Piot does have some other good things going for him. He has amazing Photoshop skills. So he let me share this this beautiful picture of Aaron. And I think it's a good a good message like measure your stuff. Maybe something to keep in mind for this talk as well. Oh, and also talking of Piot, week grab is cheating. Because it's written in pure Ruby, but it uses this object space week map, which is definitely written in C. So it's just eight lines of Ruby that delegates to this week map. So, yeah. Yeah, it hasn't always been the case. Fair enough. But still, I think it's important to point out. Okay. So, yeah, enough, enough joking and trolling. The story of this talk kind of goes a year back. Last year at JRubyConf, I did a lightning talk about some some patterns that I had been using doing stuff in a more functional way in Ruby. And then I did the lightning talk again here at our camp. And I got a lot of good feedback on it. And I kind of realized that there was so much, you know, in that topic that I could explore. And so on the train back from Belgium to Berlin, I started writing this LeanPop book, The Happy Lambda, about functional programming in Ruby. And I would love to say that now, one year later, I'm here to announce 1.0 of my book. It's not quite the case. Turns out that writing a book is a lot of hard work. But it's about it's about a third finish, let's say it's about 40 pages at the moment. Already more than 100 people paid for it, even though you can read it for free online. So that's amazing that anybody here, like, buy the book. Yeah, so that's a couple hands. Thanks so much, guys. Like, much appreciated. And I do intend to finish it. I'm not going to put a time on it this time, but but I am committed to really finish this book. I've been basically the last six months haven't been writing so much, but I've been thinking I've been exploring. And I think I have a lot of good stuff to go in there. Right, so before we talk about functional programming, let's talk about programming paradigms in general. So who recognizes what this is? Shouldn't be too hard. Just yell it. Close enough. It's not an imperative language called assembler. So assembler is kind of, you know, that's where our program history of programming languages kind of starts, right? Like, you have instructions, there's two things that you kind of notice in this assembler code. You have instructions and you have places. They can be registers, they can be memory addresses, but these are kind of the two components and they will keep coming back when you talk about writing programs. So with these instructions and these places that contain data. And so this is what we call imperative programming. State plus instructions and essentially it's modeled after the machine. So when we kind of figured out how to build machines that could do calculations, we gave them these kind of, you know, mathematical units that could do one instruction at a time. And so that's how we started programming. And from there it went on and we realized that actually programming in assembler isn't that convenient. So we figured that, okay, maybe we can just sort of chunk these instructions together into bigger chunks and sort of reason about it at a higher level. And so you got procedural programming. And then we realized we could do a similar thing with our data, right? Like take these places that contain data that is kind of related and that changes that similar points in time and that needs to stay a bit in sync. And let's stick those into a box that's called an object, bam, object orientation. Now I know I'm not feeling giving full credit here to people. Like really the idea of object orientation, and I know Alan Kay would disagree with me, but a lot of what, you know, object orientation in practice is really this. It's procedural programming with an implicit self. And so when it comes down to it, it's still imperative programming. Okay, so that's fine, you know, and we like that, we're happy with that, but is there an alternative? So, well, yeah, first of all, point out, so what is typical about this imperative programming is that it's place oriented programming. This is a term that Rich Hickey came up with.   The problem is that, you know, for programmers that's very intuitive, you know, we've been using variables, all our programming careers, and that's how we reason about things. But actually human reasoning is kind of different. Like when we think about facts, when we think about pieces of information, then we don't really go back and change existing facts. Like if I say, okay, one day it's 19 degrees and then the other day it's 17 degrees, I don't go back in history and change yesterday's temperature. You know, there are just facts that are bound to a certain point in time. And later on, you get different facts and the other facts become historical facts, but they don't necessarily become invalid. They're just bound to a certain point in time. Right. So, instead of modeling our programming languages after the machine, we can sort of go back and see what other ways of abstract and formal reasoning that humans have been using to try to specify things in an unambiguous way. Because in the end, we need to tell the computer in an unambiguous way what to do, so we need some kind of formalism to do that. And so we have mathematics, we have formal logic systems, and in particular, we have the lambda calculus, which is a formal logic system that predates computers, but that was basically devised to reason about what can and cannot be computed, about computability. And so in the 50s, John McCarty took that idea of lambda calculus and based his programming language Lisp on the lambda calculus. John McCarty was a remarkable man in several ways. He, several things that we take for granted now, garbage collection, the term artificial intelligence, like it all basically came from him.  So you kind of have the old definition of functional programming and you have sort of the newer definition of functional programming, and it's all about where you put the emphasis. In Lisp, why Lisp is functional programming is because you have higher order functions. So you have these lambdas, which are like functions, but they're also like values, like numbers, like objects, you can pass them around. So you can pass a function to a function and pass a function out of a function back as a return value. And so you get things like map and reduce, which take a collection and the function. And so this is this is kind of the original definition of functional programming had a lot of emphasis on that. And instead of having, you know, for loops with with a variable that updates, you would use recursion. It's very elegant and you kind of keep your state on the stack and don't keep so much mutable state around. But then like when language like Haskell came, we kind of started putting more emphasis on another aspect, which is the pureness and the immutability. So in purely functional programming, all values are immutable, we don't have variables, we don't have places that we can overwrite. We only have pure values that we can pass around that we can derive new values off. But once a value exists, it's kind of set in stone. So these two things, state and instructions kind of come back, but look a little bit different. So we have immutable values, like I said, they're just pieces of information that that can no longer change. And for some things, we find that very intuitive. Like we would be very surprised if, you know, we have two instances of the number 42. And I changed the lower digits of the first instance to four. So now we the first instance is actually 44. And the other one is still 42. Right? Like, I don't know if they even registered what I said, like that's such a weird concept.  But from a programming point of view, like that is not significant. You don't care which instant it is like the individualness of the object disappears and all that remains is the value that they represent. So for small things, this is very intuitive. But for bigger things for composites, we find this less intuitive. So when we have a hash, when we have an array, we find it very, very normal, kind of expected to work that way that we can shovel stuff into it and rewrite things at certain positions. Same for objects, you have an object with a number of instance variables with a number of fields, you find it very natural that you can override those change those. But it doesn't necessarily have to be the case.  You don't do that. Once something exists in the world, it's set. So that's the value aspect. Then when it comes to instructions, when it comes to functions, sort of the counterpart of immutable values are pure functions. And a pure function basically means that you pass something in and based on what you pass in something comes out end of story. This means that it can't access any state outside of the arguments you gave it. And it can't cause any side effects. It can't interface with the outside world. It can't do disk network, anything like that. If you have those, you know, if it's basically like a mathematical formula, you give it something and then it computes something and end of story. That's a pure function. So no observable side effects. And when you're using these values, when you use immutable values, you already don't have this global mutable state. So you kind of naturally go towards these pure functions. Now, this is all fine and dandy, you know, but they're just like little concepts in themselves. Now, why is this significant? When you start to add all this together, you get interesting properties. And pure functions in particular have the property of referential transparency. Now, what we mean by referential transparency is that if you take a certain invocation, so a specific function with specific arguments going in, then you can replace that invocation with its results. And your programming is still identical. The behavior is still identical. The program is still correct. And again, this seems like maybe, okay, why does that matter? But actually, if we know that a function has that property, then suddenly a whole lot of things become possible. So for instance, we can memorize it. If a function is impure, so memorizing means that you cache the results of computing the function so that when you have to call the second time, you don't actually call it. You can sort of skip that whole computation, you just take the result that you already have. And if it's impure, if it has side effects, or maybe if it relies on global states, or it might return something else in the future, then you can't really memorize that because you're not going to get the same results. Only when it's impure, you can memorize it. And similarly, if you can prove that you're never really using the result that comes out of that function, then you don't have to call it all. So that's the principle of lazy evaluation. Similarly, pure functions are naturally parallelizable. So say that, you know, Ruby, MRI decides that it wants to make your program faster, so it's just going to spin up a bunch of threats, and every other instruction, it's just going to pass out to a separate threat, and then in the end, like, sort of put the results together again, you know, that might go horribly wrong. That will go horribly wrong. And the reason is that these instructions need coordination because they're dealing with a very different state. And so when one is updating it and the other is reading it or the other way around, it needs to happen in a specific order, you can't just parallelize that. But when you know that the functions are pure, when you know that they are reference transparent, then all they depend on is their input. So you distribute the input over a number of threats or whatever, let them calculate the results, aggregate the results again. All is good. And finally, and this maybe is a bit harder to sell if you haven't really experienced this, but I think you can kind of intuitively grasp that it does make things easy to reason about, easy to refactor, basically because everything is local. You know, what you see is what you get.  So you kind of see that when we put these different ingredients together, interesting properties emerge. And I love this concept of emergence. It's also talked about in biology, in natural sciences, where you have a number of small components, a number of small rules, and they don't do so much in themselves, but put together the exhibit behavior that is not in any of the parts. So take for instance, water, you know, you have two hydrogen atoms, one oxygen atom, put them together into a molecule, have a bunch of them, put them at a certain temperature, and suddenly you get these very intricate patterns. And the patterns are not explicitly encoded in any of these atoms. It's just kind of how forces interact that these interesting properties emerge. And I think it's the same thing with functional programming. And so immutable values, pure functions, and a third one, which we'll talk about in a bit of purely functional data structures, I think when you put all these together, you really start getting very interesting properties. Now, so if that's not enough to convince you to give functional programming a try, there's a couple other good reasons. And one basically goes back to what we were saying about parallelizability. So up to five years ago, ten years ago, software had this amazing property that, you know, if you just left it alone, it became faster. Like that's, that was actually, those were the good days, right? Like, okay, it's not fast enough. Let's wait 18 months, get a new computer. Awesome. Twice as fast. Good work. That's no longer the case, or not always the case. So once chip manufacturers started going towards the four gigahertz, like clock speed of processors, then they found out that actually you get interference and leakage of energy, and it becomes really hard to, you know, make that economically viable. The challenges become much harder. But more slides actually still in effect. They are still able to put more transistors on the same die. And so they took a different approach and they started making more cores in the same processor. So now, like, for computer, for consumer devices, we're like four, eight, and it's only going to go up. And so now the question becomes, can our software really, like, make use of that? And turns out that a lot of traditional software can't. And so this is one of the reasons why people are getting interested in the benefits of functional programming. But is functional programming alone the answer? And to think about that question, I'm going to refer to an article from 2006 out of the tar pit. Very interesting. It's not too big. I highly recommend reading it. So they basically explore, they say, okay, we are facing a software crisis. Software projects have a tendency to go over their deadline, over their budget. And they believe the reason is software complexity. And then they distinguish essential and accidental complexity. So when you want to solve a certain problem, you know, your problem domain has a certain innate complexity. And so your program is never going to be simpler than that. You need just enough complexity to represent the complex stuff you're doing. But it turns out that a lot of complexity on top of that is just added by the practices, the tools, the way that we do things. And so this is considered accidental complexity and complexity that in an ideal world we would be able to avoid. And so they say functional programming goes a long way towards avoiding the problems of state-derived complexity. So they say that the main reason that you get this accidental complexity nowadays is because you're managing this mutable state. And so functional programming can help you manage that. This has very significant benefits. But also, Kaveat, the main weakness of functional programming is that problems arise when a system to be built must maintain state of some kind. And actually in the original quote it says between brackets, as is usually the case. So very rarely do we get to write a program that does not have to do any side effects or keep any states in the real world. Yes, we do need to keep state. We do need to deal with side effects. And so out of the tarp it says or proposes to use functional programming plus COTS relational model of data, basically how relational databases work. So that's interesting. That's one proposal of how to deal with this complexity. And when you look at sort of, okay, Ruby is almost 20 years old. Right? Like that's in computer years, that's like a millennium. So in the last 10 years, a couple of years ago, we had a lot of problems with this. So in the last 10 years, a couple of new interesting languages have come out that many people are interested in that are gaining followers by the day that sort of leading people in the community are talking about. And I put a few here. Scala is one of the oldest, 2003, and then 2005 F-sharp came along. And then more recently you have Clojure and then just a couple years ago, Elixir from Jose Fallin, which is quite active in the Ruby community before as well. And so what all of these languages have in common is that they take strong influence from functional programming, but they're also multi-paradigm. They are not just functional programming. They combine it with aspects of other languages to hopefully give you sort of an interesting mix of features to get your job done. So out of the tarp it says use functional programming plus relational database model. Haskell has functional programming, but it actually has this imperative sub-language that is just marked by the type system. So Haskell is statically typed, and so it's immediately obvious both to the programmer and to the system if a function is pure or not. And this gives the system a lot of power to reason about what your program does and to optimize. But at same time, don't believe that Haskell doesn't allow you to write imperative code. It definitely does. Some people say that it's the best imperative language around, but so they kind of solve this with a very intricate type system. Clojure has a different take on this. They say, okay, you know, all our data structures, everything we kind of give you our whole toolbox is based on immutability, and we assume that the functions you write are pure. Even though essentially it's just compiled to Java byte code, so you can very much do imperative programming and do everything you can do in Java, but if you use the Clojure data structures, if you use their toolbox, if you write idiomatic Clojure, then you end up with pure functions with pure functional programming. But because of that, they are able to give some neat features which are their reference types, which basically give you new primitives to deal with states and to deal with concurrency. So this is an interesting take, and other languages are starting to take some inspiration from that. So where does that leave Ruby? Except I might do it for time. So two years ago, Gary Bernhardt did this really cool talk, Boundaries, where he's basically already talking about this stuff. When you watch his screencast, I think he also regularly pounds on this. From the inside out, your system should have a core that is purely functional. For all the reasons listed above, easy testing, easy reasoning, all the benefits it buys you. But at some place, at some point, you need to deal with I.O., you need to deal with states. And you can't do that on the outside. So you need to deal with states. Impurity is contagious. So when an impure function is called by another function, the calling function is necessarily impure. Think about why that is, but take from me like that's how it is. Functions that call other functions for the outer calling function to be pure, anything it calls also need to be pure. So you can start at the center and build a functional core, a pure core, and then sort of from around that, you can call into that to deal with your business logic, and then when you get your results, you deal with side effects and state. In particular, he proposes to marry this with actors that you might know from Erlang or Go, which actually Matt's apparently I've heard is also interested in maybe getting into Ruby standard library. So that would be kind of cool. But there's one kind of elephant in the room that we need to talk about, because I said, okay, like even composite structures can be immutable. In a way that's pretty easy to achieve, like say that you have an array of 100 elements, you want to add something to it, you copy the array, you add an element to it, you don't have to change the old one. So that's the way to do it. So that's where you have to create a new environment. If you constantly have to copy everything before you can make a change. So how functional programming languages approach this is with purely functional data structures. So this book from 1999 was kind of the first to aggregate all the research on this topic. And then since then, a lot more research has happened and a lot more research has been done on this topic. So I'm going to talk about some data structures work to be able to give you those guarantees and give you those operations. But with time and performance guarantees, very similar or in the same order of magnitude as destructive sort of added in place containers, you get a technique called structural sharing. So I'm going to show you what I'm going to do. I'm going to add an extra node for a set or a hash map, but we've represented it internally as a tree structure. Now I want to add an extra node to F. Give it a child. So what I do is I copy F, add the extra node to the copy of F, and then copy every node from the top. They look like two separate trees where one has one node more than the other, but in memory they largely overlap. So this is A faster and B more memory efficient. And here I'm using a binary tree just to make this visualizable. So for a tree of seven elements, I had to copy three nodes. So that's not that good. But in practice, they're going to have two yellow trees. So instead of having two children of each node, you're going to have, for instance, 32 children of each node. So they're even for, say, 100,000 elements, you still only have to copy three nodes. And then with some bit-shifting, it's actually very fast to find that path of where you need to be. And so these, when done well can perform really well. So here we have our functional special sauce that leads us into Unicorn and Rainbow Land. But, yeah, I haven't said that much about Ruby yet. So, yeah, what about Ruby? So when you look at Wikipedia, oh, I cut that slide out too bad. So Wikipedia says that Ruby is a imperative, something-something, multi-paradigm, functional, multi-paradigm. So I don't know what half of that means, but it's supposed to be already kind of a functional language in case you hadn't noticed. So Ruby definitely takes some inspiration in particular from Lisp. So the data structures, the array, the hash kind of come from common Lisp. And with that, we got map and reduce. So we have these higher-order functions. We also have freeze, which is going to come in really handy if we kind of want to program more with values. Recently, relatively recently, we got lazy enumerators. So people are still kind of keeping an eye on that whole functional world and what's happening there. But that's essentially it. It's not a whole lot. On the other hand, you know, we've kind of seen these main ingredients that really give you those benefits of most of functional programming. And so when people think about functional programming, they kind of think, you know, the first slide I showed, the church numerals, or if you were here two years ago, apparently Jim Wierig did his Y Combinator talk. You know, this getting creative with lambdas, lambdas everywhere, like that's functional programming. But really, to code in a functional way, all you need to do is start with immutable values and pure functions. And so this is not in contradiction with object-oriented programming. They're complementary. So as I said before, have a core of pure domain logic and handle your state and your side effects outside of that. And so some things are already values in Ruby. True, false, nil, there's only one instance of each. Numbers behave like values. Symbols behave like values. And then a couple things from core and from standard library. They're immutable in Ruby, love it or hate it. But at least when they came up with path name which is essentially just a string, they learned from their mistakes and made path name immutable. So yay for that. But again, that's kind of the end of the story. But that doesn't stop us from doing it ourselves. And people are doing this when you just, you know, quick search around in RubyGems showed these 13 different gems that basically all implement some version of an immutable struct. Ruby struct class, but the result is immutable. So I think it shows that there is real demand for this. And I'm just going to show a couple of gems, sort of my personal favorites. So these are two gems related gems from the same guy, Concord and Anima. They are like struct, but with slightly different assumptions. So here I'm using Anima to make a ukulele class. It has two properties, color and tuning. And so this single line, the single include, gives me all these methods.  It's also kind of handy. And so here you can see how I use it. And basically Concord is exactly the same. But instead of a hash based constructor, you get a positional constructor. Now, this gives you attribute reader, not attribute writer, but it doesn't freeze any of the values you stick in there. So you might still end up with an object where you can change an instance variable on that object, but you can change what inside that instance variable. So it's best to combine this with another small but super useful gem, Adimentium. And so here I'm using Concord instead of Anima, but it's almost the same. I'm making a point class, which has an x and a y, including Adimentium. Just by including Adimentium, automatically all my instance variables will be deep frozen. But it also gives you the opportunity to say you want to memoize certain methods. So here I'm memoizing vector length and I'm memoizing this 2a to turn into an array. And so you see when I try to shovel this array, that's not going to work. So small but useful classes, try it out at home. Then when you sort of get to bigger structures when you really want big hashes and arrays and treat them in a functional way, the best we have so far is Hamster, which implements this technique of this logarithmic shallow trees to give you a hash vector set.  There's some cool stuff in there. And it's written in pure Ruby. So under the hood it uses Ruby's arrays and hashes, which is not always great. But they have been working hard on performance and so far, at least for MRI, it's the best we have. So I mean it's a Hamster hash but it's a lot like a Ruby hash. Except you need to write a lot of code because of syntactic limitations of Ruby, but for the rest it's not too surprising. And so you see here that I've derived a new value of the old value but the old one is still around, hasn't changed. It's basically the point. Finally there's closure, which is a project by Charles Nutter, again from JRuby. It's probably the least mature of all of these, and it's kind of cool as a proof of concept. So as an example, closure has this software transactional memory. And so you can use this in your Ruby code to have a couple of variables, basically, that need to change in a coordinated fashion just like you would have transactions in a database. So you can basically achieve what you would otherwise achieve with locks but without having to manage locks yourself. So you can do this and you can roll back and retry if necessary. So yeah, I'm going to skip over this code because it's a bit complicated and it's not that important, but yeah, basically I'm making two lists filling them with 10 different threads and in the end everything's consistent. It's basically what it comes down to. One last jam I'm going to point to so if you know a bit of Haskell or sort of that breed of lazy functional languages, one of the downsides of doing functional programming in Ruby is that because we have optional parentheses, it means that we don't get the benefit of distinguishing between calling a method and referring to the method object. So if you want to get the method object, you have to call dot method past the name of the method we want and so this kind of gets in the way of really this nice higher order functional programming but Funcify does give you that. So here I'm saying AutoCurry which means that if I call this function or this method with less than its total amount of arguments what I get back is basically a lambda which takes an extra argument and then I can compose those just basically functional composition, it's kind of like a reverse pipe and so the result is again a lambda which has composed us two operations and then I can call that again I think this is not where the big benefit of functional programming lies I think doing this kind of stuff can be awkward in Ruby and maybe it's not what we should be focusing on but it's interesting that people are sort of exploring what we can do with this so and basically like why wouldn't we have this in core like just sort of as starting point for discussion why are methods and prox not composable so we can just say okay here's a proc, here's a proc compose them so one comes after the other the result of one goes into the other stuff like that so it's kind of a starting point for discussion right and this is my final slide where I just get around a bit so I think let me take a sip so after I did this talk the last time I got the question do you recommend that we just switch to a functional language or should people stick to a Ruby and do functional stuff in Ruby and so I think we have three options option A is basically do nothing just keep writing the code the way we've always done but I think the world is going to pass us by there are lessons to be learned here and I think we need to start paying attention so the other options are should we start using a functional language and I think if you haven't yet or if you haven't much I do highly recommend it closure is neat because it's dynamic so that's kind of easy if you're kind of afraid of very complex type systems or elixir because it looks a lot like Ruby even though once you get to the details it's very different but so these are definitely nice languages to play around with or if you want something a full type system try Haskell and then come back and see what you've learned there I think the danger is that we've seen with people writing these gems people are already trying to do this stuff but the ecosystem is not there the mind chair is not there and so we're going to start losing people that get disappointed and so I really hope that as individuals, as a community also together with Ruby Core we can think about that Metz in the latest KaiGi apparently said he started thinking and dreaming about Ruby 3 you know should we have persistent data structures in standard libraries should we have functional composition in Ruby Core these are questions and I don't have definite answers I also don't say that any of the code that you've seen here or any of the code in the Happy Lambda is how things should be written but I really hope that we can sort of start this discussion and together figure out how we can take this awesome community and not lose it but sort of take it into the future so that's it Thank you very much we have time for one question if anybody does have a question one question Aaron want us this morning not to allocate too much objects aren't you afraid that if you do this in Ruby you will allocate a lot of objects and make the program very slow yeah so that's a good question and it's sort of the typical first reaction like what about performance I think at a first level yes you tend to allocate more and garbage collect more but that's only on the surface level I think when you really start using this in earnest you're going to start writing programs in a different way and actually by making good use of persistent data structures you can get much more because it does more we saw that the command pattern is used to implement under redo if you use persistent data structures to represent your full state then you just get that for free you get history for free and depending on the type of application you're writing I think the optimizations that become possible under the hood actually might surpass the short-term win of small optimizations so I'm not saying that it will be faster and I think in many cases it might be slower even then measure and ask if you really need to speed it's a very nuanced answer it depends on your application that is all we've got time for questions there so thanks for watching thank you