 Good afternoon. So the lunch was great today because I'm talking, I couldn't As well as I had yesterday My name is Pushkar. I work for a team called Rantimes in IBM So I'm going to talk take you through This new language. It's it's not new. It's two years old as of now called Swift There's my Twitter handle Pattern of my Twitter handle is very similar to Sachin Tendulkar's But I did it before him You can also follow me on Github. So the recipe for today is Some introductions about myself About my company. I mean what we do in Rantimes Also, I would I don't want to directly start talking about Swift. I just want to Tell you a story from the beginning of You know the actual birth of functional programming and how events unfolded to reach languages like Swift and go and rest very short one nothing great about it I'm most of you who have you know been interested in functional programming will know it, but I just wanted to Maintain that continuity just didn't want to pitch into Swift and start Then I'll just take you through basics how to write. So I'm planning to do a hands-on here if you have a Mac you can use the playgrounds or Export project if you don't have a Mac windows, I'll tell you how to do it in the browser if you have Ubuntu installed you I'll tell you another way to run Swift So I'll take you through closures map filter reduce Lazy sequences currying pattern matching pure functions and memoization and the last one is Start because I'm very new to it if you have questions then we have to Think about answers together It's fun cross applicatives and monads and so So some introductions about me functional programming and so so I I I started working in IBM eight years ago. I'm still in IBM. I started with Java just in time compiler. I used to work on customer crashes. So when customers face Crash in Java, you know, they're running the Java app and suddenly goes down and they get a core dump Sometimes 16 GB core files They just give you the dump file and solve this problem. So if it's a problem in the just in time compiler, you have to sit You know dump all the instructions Keep looking at the instruction manual or move read and whatnot. So I did that for five years Only reading assembly instructions in our PC x86 and so on Then I switched to class library development By class library development. I mean all the Java standard library classes. So my team Contributes to open JDK. So but when I was working on it, we didn't have that push to contribute to open JDK We maintained our own Libraries and we work with Oracle for that last last year that's December of 2015 Swift was open source and we start we started working on bringing swift to Linux It's a community effort and we are involved. We are a part of the community So same who am I? What do I do? I'm I've already told you that why and how am I here? So what is my functional programming story? So I had I was never Somehow the term functional programming never caught my attention until the last year. So I heard of this debate in the press back in 2008 when I joined the industry are Saying, why don't we have closures in Java and I said, what are these closures? I'm not sure and I don't know why these people are fighting I Left it there. I did see a couple of posts on functional programming. I never cared to look into what that is in April last year that is April 2015 I happened to attend a conference in Bangalore and One of the keynote speakers was Venkat Subramanian. I hope all you guys know And then I was enthralled and Then I attended all his talks that day and in a day. I was brainwashed In one day, that's the power of that man I was brainwashed in a day started looking at Java 8 started laying around with Haskell though. I didn't Go much further with Haskell, but I got into the you know that bug hit me bug of functional programming hit me and After that, I offered in this con attended this conference last year learned a lot I actually got a direction about how to go about learning what I like to do So that's how I'm here What my team does just a short slide we have our own Java runtime called J9 It's open source now in case you're interested you can just Google for it and visit the site Then we also have something called the open managed runtime, which gives garbage collection and jet services If you want to implement your own language You can use what is called OMR This is also an open source project So there are implementations of Ruby and Python running on the JVM using OMR We also contribute to the open JDK then there are people who work on the community node.js effort and the express.js and The last two have Started just this year So I'm a part of the Swift Foundation libraries team. So we work on If you okay one minute a show of hands, how many of you are Swift programmers here? That's low fine, so I'll do my talk likewise so Swift Foundation libraries are some Utility libraries which are built on the top on top of the standard library and I come to that but We are involved in Swift libraries and dispatch There's there's something there's an concurrency framework called dispatch or the GCD or the Grand Central dispatch So we are also involved in that and there is our web services framework for Swift folder called Kaitura or some quality to rise So let me start. So I like this picture a lot We can assume that the beginning of all creation is the lambda so these three people were very instrumental to The birth of functional programming. So leftmost is Alonzo church. So church was uh Church was interested in coming up with a theory which described mathematics Okay, like it's like a meta theory which described maths and He apparently terribly failed at it, but his work got Used to come up with something called lambda calculus lambda calculus is the seed of Programming the second picture is of Stephen clean that person Actually came up with the recursion theory. So recursion as John said today. It's it's it's it's not it's inseparable from functional programming So clean was the one to come up with recursive function theory And the last guy there brilliant app during I have starred him because he was not directly involved in the formulation of lambda calculus or The recursive function theory he was Alonzo church's student and he proved that Church's hypothesis that is lambda calculus was during complete So, you know, what is the meaning of during complete a language is during complete if any problem solvable in this universe can be solved Using that language. So he proved that lambda calculus was during complete which meant There was an alternate discipline possible Functional programming takes a mathematical approach to programming. It's based on lambda calculus category theory and type theory as against imperative programming, which is a very pragmatic approach. So Let me go to the next slide. Why why I say it's a pragmatic approach. So these were the early adopters these languages so list came out in 1958 and John McCarthy was who the the creator of list was in was highly influenced by Church's theories and List was the first language which adopted functional programming. Now, it's important that it came out at the same time as Fortran roughly the same period and These were two parallel disciplines because Fortran was based more on a practical approach programming so before as John said today before You know compilers or languages came people used to hand write assembly code And when you hand write assembly code, you're looking at Memory as a as an array of bytes. You're doing everything one word at a time So if you have to print a string you go You know the location of the first byte you go fetch the first byte printed second by print it You're doing everything word at a time. Now that thinking came into programming even for languages were created That particular thinking of doing everything one word at a time you it Or flowed into programming whereas the parallel stream that is Function programming was born in mathematics So list was the first one. I think this had many flavors after that a scheme bracket closure so ML was the second which inspired OCaml and F sharp Miranda which inspired Haskell was also one of the earlier doctors and there was Erlang and I think Haskell was the I Mean, I personally feel it was the first Most successful functional language because it is purely functional all the other languages Don't accept Miranda because Miranda is what inspired Haskell don't enforce functional concept on you Then in 1995 after the JVM was born people started thinking of functional programming on JVM on the JVM Groovy Scala, so Java was lagging behind Scala was Scala actually Went past Java when they came up with functional programming then there was closure finally in 2014 Java Uh Suckoomed and they said okay. We have to come up with lambda in the stream But after that if you've noticed because a giant like Java has started has started talking about functional programming The world has started talking about So after that there was a thought Why is is every application supposed to be running on a virtual machine do we need that And then people started moving away from virtual machines and back to native languages. So before we Had these virtual machines, you know JVM and V8 Python We did have languages like the old languages like C and C++ which were compiled and ran on bare metal They didn't have a layer in between so People started thinking to go back Complete a full circle and go was born in 2011 rust in 2013 and then Swift came out in 2014 Now these languages are called modern native languages. Some people also add another Language here That is what they call it modern C++ That is I think based on C++ 17 and C++ 14 standards because that has lambdas and all that but largely these three are the languages which Are called modern native languages a modern native languages have three major requirements. They have to be fast because The sole purpose for you know resorting to them was to avoid the performance for either The performance degradation given by virtual machines They have to be fast. They need to be safe you have to ensure compile time safety because a Jao virtual machine can give you runtime safety you have Exceptions and all that but once you don't have a virtual machine your safety needs to become needs to come at compile time So safety was one requirement and the third one was expressive nature the language needs to be very very expressive and Somewhere these two requirements I think Let to these language designers to embrace functional programming Because functional programs when you write functional programs you need a very very expressive language You don't want boilerplate code there and of course safety comes with a good type checker and good type systems So Swift was created by a Person called Chris Lappner. He was actually heading the the LLVM team He was head by Apple in 2010 and asked to work on a very secret project and in 2014 WWDC Apple You know announced this programming language But this is a modern native language. It was expected to eventually replace it is expected to eventually replace objective C Though that's happening at a very as a snail space here in India It was open sourced in 2015. Now. That's a very very prominent milestone because I'm talking to you about swift and I don't have any mobile background any mobile development background I'm talking to you only because swift has been open sourced and there is an effort to make it work on Linux So initially it was restricted to Apple platforms just like objective C if you wanted to try swift you needed a Mac It could your code put run either on a Mac An iPhone and Apple TV or I watch these these together are called Darwin platforms But now it's available on Linux. You have to visit swift.org and you have downloads on for Ubuntu there Swift is multi-paradigm swift does not it's it's not purely functional programming language like husky And if you visit the Wikipedia page, it's a borrows heavily because Swift has been created using the best features from multitude of languages Now when I meet people in in meetups and I show swift code to them Some people say it looks like Python some say it looks like JavaScript some say it looks like sequence That's because it has it has the best features from most languages And I always tell them that whatever language you come from you want to find swift similar to that language because that is how It has been designed It has static typing And there is type inference. So I think most modern languages have type inference In my perception swift is very intuitive for once you get an initial hang of it You can just guess how to write how to go about solving your problems. That's it That's been my experience in the last six months. You just write some quote and it works. That is how it has been designed It is very beautiful. Of course, beauty lies in the eyes of the beholder, but I think it's very beautiful language It has a good compile time safety Optionals, I'll talk about options decent functional programming aspects. I'll cover them today The only problem is memory management can be painful at times if you are working with When you're working on the server side application server side with Swift The automatic reference counting there is no garbage collector because it is not It's it doesn't have a virtual machine Though God also doesn't have a machine. It does have a have a garbage collector, but So it doesn't have a garbage collector and you have to Sometimes manage memory on your own sometimes not always I have come across situations where I had to hold on to memory not let it You know be collected So goals for the next eight. Yes, I have it 75 minutes. It is appreciate some general functional concepts Start playing around with Swift's functional constructs. It's also some simple problems and we'll try appreciating Those three Functors applicatives and monads So if you're interested in following me with the hands on You have three options. You don't have a Mac You can use what we call the IBM Swift sandbox. I'm going to use that So I'll tell you how to start using it. It's it's to be used in the browser If you are a Ubuntu and a command line interface fan, then you can just visit swift or talk Download the latest binary if you have a Mac, then you can use export So let's get started. We will be learning one concept at a time These examples are highly contrived. They are very very academic in nature. So They may relate They may not relate to the real world And the third statement is what people say that whenever there is a functional programming tutorial Fibonacci and prime numbers have to come in why but you just can't do without because they are really good examples to I'm going to stop the slideshow So if you want to use the IBM Swift sandbox, you should just Google for IBM Swift Sandbox and the first link should take you there It is it's based on Linux. So when you when you write and submit your code, the code is packaged send to Remote Linux machine. It runs there and comes back the results are sent back So here is how it looks. So I'm just going to run Hello world start off Now let's start. Yeah, I also have a Git project here, which I created yesterday In case I stumble And if you can't help me out, I'll fall back on these code snippets The left side if you're using this box, the left side is where you write your code and the right side is where you see your results So let me run it once Is it visible to the last row there? Do you want me to increase the Are you able to see the code? So closures are You know, they are like lambdas in Java there's the The general concept of a closure unnamed blocks of code that can be passed around They capture the context Instead they capture the variables also. They are typically supposed to capture only values that are only constants But instead they capture variables as well and even after you you send a closure out from a function Somewhere else you can actually change the variable from that But we need not use that because I don't think that's That can fit into functional programming. So we'll say that they capture only Values the major use case of closures is asynchronous programming. There's a lot of asynchronous programming happening in Swift you know Rx Swift and there's URL session and Alamo fire and all that When you say asynchronous programming you are actually sending a completion handler a completion handler is nothing but a closure Which has which is supposed to be run when a certain condition When a certain event occurs So for closures, I'll take you to the basic syntax. I'll show you how type inference and implicit returns work there Then there's something on shorthand. So let's start. So here we'll try to write a generic binary operator. These are very simple examples of Highly academic and contrived. So let's write a generic binary operator So you may if you don't understand any part of the code, just feel free to enter Now when you say you're when you're declaring an argument, you have to so There are two names for it one name which is used by the Function that is calling your calling you and the other name which is used internally So if you if you want to allow people to call your function without any argument name, you just write an underscore here. So Binary operator, so let's say X and Y and the third one should be a closure because we don't want to we want to make this a generic binary operator and Generic reminds me of generic Let's make it generic. Here you say I will take a function which takes two arguments of type T and returns an argument of type T and let me call it If you don't have the underscores then when you're calling it, you'll have to use X colon You'll have to use a named argument. I don't think the compiler for that's that's that's left to the compiler I don't think it follows the order but that is more of something which is carried over from Objective C because Objective C since 1984 didn't have Did have these argument names external names and internal names. So Swift is just carrying over It's a baggage So this will return T And I just say Return of X, Y Let's say it compiles So what I'm doing here is defining a binary operator just just ignore these keys. They are all the generics here. So one operator, second operator and an operation that operation takes I have to specify the type of that operation. So it is taking two arguments of type T and returning an argument of type T and finally the return values of type T So if you don't understand this, just let me know you can spend more time Now, yeah, so underscore X. Let me do one thing. I'll just So let's say a function double say X into two X two Now I say X int return X into X Now if I have to call X to Typically we will say X to write But here it says there's a compiler error. It says missing argument label X because when you are defining an X, you have to call it like this. Yeah, that's just a warning. Alternately, you can also say Y X and then you can use Y here if you use underscore You're telling the compiler that I don't care about argument names. If I just say a print here. So back to the binary operator So let's pass an addition function now So binary operator of one to and then I will write the first closure and it's like this a int in Return a plus B. Don't worry. It's not this verbose later, but just to show you all possible ways of doing it. So what I'm doing here is I'm passing one to an operation which will add one So it gives me three. Now if I just say This and I say four should give me eight. Now you can actually reduce this closure. It need not be so verbose So what I can do is I can remove this return return is implicit and I can also remove these types and just say a B run it It again. So let's try something else Binary So this closure is the last argument of that function. So Swift allows you to do Pass it after you close. Okay, let me not talk about it. Let me just show you. So instead of passing this As an argument, you know, before that closing Brace, I can write it like this a B in a Plus sprint X1 Should be hello world. Yeah, so this is the the other way. This is called a trailing closure. When you have a trailing closure, you can actually push it out You know of the other function call and write it after your function call is over. Yeah, only the last Now something shorter than this. Let me remove this In a closure, the first argument has an implicit name and that is $0 And the second argument has an implicit name $1 This also is a closure. I'm running it. Hello world Doesn't stop there. Operator closures are something cooler than this. So let me remove this And I just pass a plus here. So you saw from where we started and how we went on reducing the port and this is how This is how beautiful Swift is perhaps. Yeah, plus is defined as an operator. So you can actually say plus You know, following the Referential Transparency you can actually let's let's see if it works Plus one I'm not sure never done this Doesn't work. I think it is Yes, special handling. Yes, yes. Yeah, it is. So I think that is what I wanted to tell you about closure. So As we write the map filter reduce functions will come across more and more closures. Now, let's talk about higher order functions This is a higher order function because it is taking It's taking code as an argument You can also pass functions instead of that Code that so higher order functions are any function that takes a function as an argument or returns a function is a higher order function Everything else is first order function So derivatives are the are a very good example of higher order functions. Just think of them You're when you're doing D by DX you're working on a function and you're returning a function when it's only f of X you're taking a function And it's it's mapping to values. So rather you're mapping values to values You have a domain and a range. So you're mapping values to values. Those are first order functions Are mapping functions to function. So D by DX is taking a function. The output is a function integrals input is a function output is a function So those are higher order functions All other functions which map values to values are first order functions So we'll see passing closures to functions Returning closures functions. So let's extend the same example So what I'm going to do is I'm going to define a function called adder So adder will basically return a lambda which adds Sorry a closure which adds two integers here So I would say return a b in a plus b So this should be returning these arrows are a problem sometimes Like has killed too many arrows. Yeah, sorry Now what I can do is I can call the binary operator. So adder is a higher order function because it is returning a function a b a plus b it's an anonymous function is being returned Now I can say 100 and 200 and I can just call adder there just print it Now you can actually reduce it by only one step. You can say $0 plus give you the same output But if you say just return plus that doesn't work So let's just for the sake of just add a concat function for strings Returns a string a function which takes two strings and returns a string same thing again You can actually write a generic there showing it as an example Just say binary operator So we saw what are how higher order functions are written It's very simple binary operator is a higher order function because it is taking a function and adder and concater are higher order functions because they are returning a function Here. Yeah, this is this is needed Yeah, it doesn't so you have to I think you have to at least mention the type once other than the primitive that is integers doubles and all that you have to mention You could use any that's just right. Yeah, you could. Yeah, actually I was saying that you could use a generic. So what you could do is You could say T T and just say adder here should work binary operator plus cannot be applied on to T. So let's move on next I want to take you through map filter and reduce these are you know these are three common operations on sequences Apply the same transformation on all the elements of a sequence select a few elements from the sequence and reduce all elements of the sequence to a single element So how many of you have tried functional programming here. So most of you have must have tried map filter it was something very basic. So let's try it So I need not take you through the semantics of map filter and just write a program which uses all these three So again a prime number sum sum of squares of all primes between two and start let's start with a function is prime which takes an integer returns a Boolean Now if you want if you want to test for divisibility you can actually test from two to the square root of X but that will make things complicated. So I'll test from two to X minus one You get it right for prime number if you will test divisibility is enough to test it up to the square root you know the floor or the ceiling of the square root But let's do it up to X minus one so return X is greater than one and now I want to divide I want to try dividing X by all numbers between two and X minus one So I'll use a range here two to X this is a close this is a half closed range it is called because when I said two dot dot lesser than X it means from two to X minus one If I added another dot here it would mean two and X including both both includes inclusive of this now I will filter all those divisors which were able to divide X Is that filter clear? What I'm doing is first of all X should be greater than one because zero and one are not primes and then I am taking all the integers between two and X excluding X And filtering out only those which are dividing X and then I can say the count of that should be count of that should be zero which means there are no divisors is that is that simple or is it complex Are you following what I did here so this part is clear now here what I'm doing is I want to I'm taking X and I want to divide X by all numbers between two and X minus one And I want to make sure that there are there is no such number which divides X so I'm filtering it using X percentage dollar which means each of these numbers will divide will try to divide X and if it is zero it will go into an array So if the count of the array is non-zero which means that there are divisors between two and X if the count of the array is zero it means there are no divisors Yeah we don't need to put this so it's the only arguments it's a it's a trailing closure got it so let's print is prime one that should be false is prime two should be true True is prime line should be false and 13 should be true so we have a function is prime now the problem was find the sum of squares of all primes between two and n so let's write a function sum of squares and let's let's take n as an argument and we return integer here now I'm I'll do the same thing from this time I'll run from two to n it's a range from two to n and I'm going to filter out only the primes so I want to say filter is prime It is it is it looks like Java 8 and then I'm going to map it to the square and then I have to have to find the sum of it so I'll just say reduce start with zero just return So sum of squares let's take five so if you take five will be two square plus three square plus five square that is 38 let's print it out you want any other numbers So we have written a code that writes the sum that that calculates the sum of squares of all primes of starting from zero to a particular number now this is very concise I don't think there is any boilerplate if you think it can be reduced further I'll be happy to do it Performance Swift is a native language so I don't think anybody has made performance tests of functional code versus non-functional code I have not come across any but there have been performance benchmarks using something called reference types and value types So if you if you start using Swift you have the concept of a class in the concept of a structure a class is a reference type and a struct is a value type when you say value type you don't have so when you say a struct x and you say y equal to x And then eventually you change y x and y will point to two different memory locations so those are value types so value Apple is pushing Swift programmers to start using value types because it's safer to use value types when you're doing concurrent programming Now there are performance benchmarks which prove that the performance of value types is not as good as the performance of reference types so that's the only performance comparison I've come across If you use a class here it's a reference type if you use structs structs are just like classes only instead of a class you write a struct in your program but the compiler deals with it differently Yes it's just like a class from a language perspective but it is very differently welcome and that was the next topic So by default sequences in Swift are not lazy so if you want to make them lazy you have to use .lazy that let's see an example for that It's not going to cause any improvements here I guess So the next one is as you guessed it's about lazy sequences so map and filter are by default eager operations in Swift Unlike Java 8 streams which are everything is lazy in Java 8 streams there are non terminal operations and terminal operations So map, filter all these are non terminal operations only some average min, max, reduce basically all reductions are terminal operations So in lazy sequences computations are deferred until results are in demand Closures can be stored and executed on demand so you avoid needless storage and computation So let's see an example of an infinite sequence and lazy arrays So let's define an arithmetic series which is infinite So you can say in arithmetic series you have an A that is the first element and then there is a common difference So there is how do you call them I'm not sure about the type here let's use sequence and try So return sequence this is how you use it you say first and then next So you say the first element is something and to calculate the next element you give a closure Let's see this compiles it's not compiling I'm not sure what the type of this should be So let's check this off I'll just say let arithmetic series equal to this one So let's start with 10 and common difference of 3 Now if you print this now this is an arithmetic we don't know where to stop It is starting with 10 and every next element is calculated using 0 that is current element plus 3 Now if I print this arithmetic series it says unfold sequence because it has just created a recipe It has not actually run the calculations it does the calculations only when you say call a prefix of 10 Prefix of 10 means give me the first 10 elements of that infinite series Still it is not still it is lazy what do we do for that So prefix is also not giving you the actual sequence I think the actual it is asking you to give some operation So that's what I had done so you can actually say this So what what I've done here is this is an infinite series and then I said arithmetic series dot prefix 10 Still it gave me back a lazy sequence and only when I said you reduce it by adding a plus That is when it actually calculated the elements of it the only the first 10 elements I guess And then it added them and give me back the result Now let's see it in let's see if we have a map and a filter how many times they are called if you have a normal sequence And how many times if you have a lazy sequence so let's have a function called cube plus 2x it takes an integer Returns an integer running short of time and you I'll return x x x plus 2 into x Now let me also have another or is odd it says return x percentage 2 equal to equal to 1 So there are two I'm writing two functions one is calculating the Sorry this should be bool one is calculating the cube plus two times of x and the other is returning if it is a odd number Now let's define let's let's put prints here print print hello say one two ten cube plus two x dot filter Actually it should be first because this filter won't work otherwise is filter is odd dot map If I just print this see what happened it ran the filter in the map the filter 10 times Okay, then only five were filtered out because the others were even only five watts were filtered out and then it ran the map only five times and it gave you this Instead of this if I use lazy here nothing's going to happen for now it's it'll just give me a return a recipe of what needs to be done Here that recipe is very ugly though it's actually the name of a class I think No we are actually printing the object returned by this expression which example I think that will happen if you say for each print I'm not sure but let us try printing every element is different from printing the But for each for printing is violating functional programming because you know why for each is taking a closure I'm not sure I never tried this anyway for each you can't have printing for each because it's a side it's a print is a side effect And closure should be free from side effects so now I just print the first element of this I'll say dot I think I can say dot first yeah and I said dot first it ran hello once it found that it is an odd so it ran high And then it printed three so this is this is the beauty of lazy sequences only when you need a computation you are running it Unlike the default in Swift which is eager so do you get this point let's move You know who this guy is that is optional I'll take you through options very important so how many has killers here So this guy has killed curry he was a mathematician and the language has killers named after him and his second name is also used currying And you know there is also a language called curry but currying as a concept was introduced by someone called Sean Finkel But Haskell curry was working in parallel to Sean Finkel apparently I've read so and currying is a better name you it will be very difficult saying Sean Finkel Caring and uncaring is better so currying is applying one argument at a time to multi-argument function so lambda calculus inherently is if I'm not wrong single variable So then the question was how will you apply multiple variables how will you accommodate functions which take multiple variables and the answer was currying Which meant you apply one variable at a time so if you have an addition function you apply one way for one variable first it returns a function with a single variable And then you apply that next variable so they become very relevant in the context of higher order functions I think if you talk about real life then I think they improve readability But there was one more person who was talking about F sharp and he said that they help you abstract behavior between layers so that's a good point but because I've never used currying in my day to day job But I can give you an example here so let's say you have composition so let's say we have some nouns here cat now I want to I want I'm interested in two operations one is Append you know prefixing a so making a cat a dog a pen a paper a chair and then prefixing the the cat the dog the pen the paper the chair so I can write a lambda for that a closure sorry So you can say in nouns so if I wanted to append a so I can say in nouns dot map a plus zero because we don't have time we'll violate the principle so far so it's putting a dog a cat's one Now I also want to end the sorry and the so it becomes the other now if you show this code to someone he he will not understand what is this okay fine it is appending a space but what is the space What if he doesn't know this array so what if you want to sound more declarative okay so what you could do is you could declare a function that appends a to a string and returns a string so you will say return a plus x and the same thing you would do for the and then you would say append a and here you would say append the Yeah but the problem here is there is repetition here there is repetition here if these functions were big then there would be a lot of repetition you're doing the same thing twice so the question is can you do it once so anybody would say just say append here and just say prefix and just call it make it a string then just say prefix dot x and just remove this and I'll just say append a $0 but this is as bad as the first as bad as the first one it's not working oh sorry so this should be like this I think this was the problem yeah so this is as bad as the first one so why don't we keep this function and correct so I would say append a is a sorry I would say prefix a is a indefinite article so indefinite article but here I'll have to change this so instead of having this syntax I'll say append is a function which takes a string and returns a function which will take a string and return a string this is where it gets a little painful too many arrows ok now prefix indefinite article can be append prefix definite article can be append the and then here you use map prefix indefinite article and here you use map prefix definite article this combines unresolved identifier at 22 yeah this is yeah this should return a closure so the closure would be x in prefix plus x yeah so this is what currying is so you're applying only one argument the first time and then that that half baked object is a function which will take another argument and that you're passing to the map so as I said currying becomes relevant in the context of higher order functions like map yeah exactly you can say prefix $0 so that's about currying I'm really short of time so let's move to pattern matching I had a lot of quote to write here I have only half an hour left so pattern matching so I'll show you because none of you have have you tried the simple algebraic data types you know list to list to RA2 list and list to RA so something like that we can do in Swift so first I'll just copy paste code now because I'm running short on time so let's see so this is a function this is just to show you the power of the switch case now I want to traverse a square which is one which is in the first quadrant so one corner is located at 00 okay I want to traverse it in the anticlockwise direction so I want to go on the so for you I want to go on the x axis first then up then here and then down now imagine doing that using a for loop you imagine the number of conditions you will put there but with pattern matching in Swift it's really easy so what I'm doing here is I'm writing a function called visit s is the side of the square x and y are the points at any given moment so as soon as I enter this I say I have visited x y and then to move to the next point case 00 is return because I'm starting at 10 and I want to come back to 00 so case 00 is stop this is for the horizontal line which is on the x axis it is from it's a range so you're switching on x and y if x lies between 1 and s and y is 0 just move ahead so you say visit x plus 1 0 or you can say x plus 1 y then the next case is for the vertical line which is from s 0 to s s and this is the pattern for that and whenever you if your x y matches this pattern you're just moving one point upwards the third case is for that horizontal line on the top okay your x is between 1 and s and your y is constant there at s so you're visiting you're just decrementing x in that case x minus 1 y and the fourth one is you're coming down so this is a very nice example of using pattern matching in using switch case if you go through the apple dogs there are actually 6 to 7 ways of doing pattern matching this is just one of them so for a square of say side 5 if I run this code it prints how it visited so you can see here 1 0 2 0 then it went to 5 then it started growing up and came back and it stopped at 00 so this is how cool it is to use pattern matching using the switch case one question you can ask here is so do you see a problem here what if the square was really huge what if it had what if the side was a million no no this is not easy but what if this was huge there's a recursion here you would hit a stack overflow but there is tail recursion in swift you need not do anything special for it so there are block posts which actually study the compile code and prove that tail recursion is there so now I wanted to show this particular example of pattern matching something like what we do in Haskell so let's say let's so here we'll talk about enumer enums so let's define an enum so enums are like something like algebraic data types I don't know the text but enums are enumerators of course but they are not as simple as the enumerators which come with you know the traditional languages like java cc++ so you can see a enum list they are actually a collection of types so enum list I can say it can be a list can be this cons is from Lisbon Haskell a cons which has an integer and another list or it has nil so which means a list is either a node which has an integer and another list or it is nil so it's defining the list recursively so if I compile this it says you are using this list recursively so you have to add indirect here so when I say this it takes that definition now I'll just copy paste code now what I want to do is I want to convert an array to a list so I write a function to list which will take an array and return a list of this type if you have tried this simple example in Haskell you will be able to relate to it what this is doing is whenever you call list it is switching on the array if your array is empty it is returning nil because list cons can represent list nil also represents list so when your array is empty it is returning nil if your array is not empty then it is extracting the first element it is putting it here and then it is calling two list on the rest and that is the second associated value for this cons yeah the dot is because this is it should actually be list dot nil and they should be list dot cons because they are defined as a part of the enum but Swift says you are spared of that pain as if it is big thing and if you add just a description yeah so so what I want so I am built so just look at the enum so you have the enum has two types it's a it's a it's a it's a collection of two types one is a cons and the associated values are an integer and another list just imagine a list every node of the list has some data and it has a pointer to the list the rest of the list every node does that except for the last node which has no pointer okay now here you are saying list is either an element which has an integer and a list or it is nil because even if you consider the last element it has an integer and it has a nil list so whenever you are constructing it from an array so you switch on the array if the array is empty there is nothing to do so you just return nil switching on the array is so it will it will try to match this case no no no this is matching directly on the array see you are saying array let x where x dot is empty so you are in short you are doing x equal to array and x dot is empty referential transparency and then you return dot nil yeah and then otherwise you just extract the first element you put it in the cons and then you call to list on the rest it's a recursive thing now with this description if you simply call this print l this is how oh my god you should say list l dot description this is how it looks this is a very basic function in exercise in Haskell actually yeah it's a pair of values it's a pair of an integer and another list so see this cons is one here and the rest of the list the rest of the list this cons is two here and the rest of the list cons is a tuple cons is a tuple of an integer and a list another list no so this is actually I wanted to show that this is just works just like Haskell Haskell has I think all fundamental exercises in Haskell have this example so I wanted to show that algebraic data types are something which are simulated by enums okay so we have 15 more minutes do you want to so I have I have two options either we do only memoization or we do functors applications and monads so just a short description on memoization so yesterday there was a big debate on referential transparency right there is a concept of pure functions a pure function is a function which for any given value it will always give you the same output okay so Fibonacci is the best example for a pure function because there are no external dependencies there are no side effects which are being factored into it any value it will always give you the same it will be always mapped to the same value in that case why can't you cache the values that's the rational behind a memoization I think in closure memoization is very it's built into the language but in Swift it's not built into the language you have to write your own function to memoize and it does give you speed up so if you are interested just visit my Github profile there is a folder called functional cons and in module 4 there is a memoize function this is the memoize function basically caching values and instead of calculating them again and again you are reusing them okay so I will move to functors now now I have also had a very basic understanding of functors applicates applicatives and monads so in a nutshell you can say that they are containers which hold objects and they follow certain protocols you know they give you they hold objects and they expose a certain interface which you can use for your own benefits so a functor is very simple if you have a function from a to b then for a given functor if you apply that function and if the functor is containing a then the resultant will be a functor with b now let me make it very simple I will use arrays because we have noted seeing what are optionals so say we have low now this is an array of strings what if you wanted to convert it to an array of string lens you need not do much you just have to say map dot characters dot count yeah so just look at it this way you have an array which is a container and it has some strings and now you are doing an operation on array without fetching those strings one by one and the operation the results of the operation of the results of that operation are again in an array are you following it you have an array and you are applying a particular operation now actually this operation is what it's a function on which takes a string and returns an integer dot characters dot count now you are applying that on an array you are applying that on a container of strings and what you are getting is a container of ints so it is of that you can say that for f from string to end you are able to apply it on an array of strings and get an array of ints so it is the quality of that array which is allowing you to apply a function to all its members and throw out result which is again in an array that simple thing is called a function anything any container or as it was being explained there in the previous session any box so you have a box you have some data in it and you apply a function which is actually defined on that data not on the box and it gives you another box with the output so here we had strings in a box we applied a function which was actually on strings and return and it was supposed to return integers and we had a box now and we have a box of integers so we have two things we have a function from string to end and we have a box of strings and what we are getting is a box of integers we never had a function which ran on a box of strings we had a function which ran on strings so it is as simple as that anything which can implement map is a function in terms of swift outside also the very simplistic definitions there is a huge amount of map involved behind it I am not sure how much of it is there but in simple terms anything on which you can apply a map is a filter so optionals so we were talking about optionals right so in swift we have this concept of optionals where you can say I can say x int equal to 10 and then if I say print x is going to just print 10 but if I can if I put a question mark here which means x is an optional int which means it can either have a value or it can be nil so if I print x now it says optional of 10 it doesn't say 10 now if I just say nil here I can say nil here so it says nil now the point I am making here is optional is also a functor why because let's have a string equal to hello now again the same thing characters.count is a function from strings to integers now let me apply that here x dot map so map is not only on arrays it can be on optionals also x dot map dot characters.count what do you think the answer will be x is not an array but still you can apply map because map is not only on sequences it will be optional of 5 because optional is a functor anything inside the optional if you apply a function which is so a string is make I'll keep it simple see let's go to the slide here again yeah yeah yes so you have a function which is from a to b ok and then you have a wrapped in a box and you are applying this function on a and you are getting b in the same box then that box is a functor both the boxes have to be the same time so the box is a functor now so and one more profound thing about this is if you have nil here there is no problem nothing will happen even this will be nil so that is what the next picture meant if you apply that function on an empty box you are going to get an empty box so just imagine the amount of checks this is reducing otherwise if you had to do this without a functor everywhere you will have to unwrap the optional so optional unwrapping is so when I say let x into optional equal to 10 it says optional of 10 right if I want to get 10 I use this bang here you are asking so then it says 10 so everywhere if we didn't have the functor we would have to check for nil only if it is not nil then you know unwrap it so that forced unwrapping is not a good thing every time it's a guideline that every time you are unwrapping you are doing this you better check that there is no nil otherwise you are going to crash yeah so actually nil checks were missing in swift and later they realized it and then they moved it to the library saying library should take care of this optional is the point then it will it's going to crash error running your code stack prices also no no this is not a compile time error it actually went to the server it crashed and came back it doesn't give a compile time error yeah pardon me I didn't get it yeah so here if you in typically no if you remove the bang it will just print nil but we are expecting an integer right so we have to use the bang so what typically swift programmers do they say if let x1 equal to x this is unwrapping and then print x1 you can use guards also so it's not printing anything here if I say 10 it will unwrap and print this so all these are not necessary when you are using functions that is the point now talking about applicatives so in functions we saw that the function was from a to b and we applied it on a box containing a now applicatives go one step further where the function is also in a box this one you have a function from a to b and the function is also enclosed in a box and you are applying that box function on a boxed data and you are getting another box data if either of them is nil if the function is nil nothing happens if the data is if this box is empty nothing happens so one example for this is sorry yeah so like we have map for functors swift doesn't have anything for applicatives though you can extend the optional type to work as an applicatives so that's what I've done here let's not get into the details of this code because we don't have time so what I'm doing here is I'm defining a function called apply so I'm extending optional here so you can extend any any data type in swift so I'm extending optional here and only in short don't go into the code in short only if the incoming function is valid I'm calling map otherwise I'm returning none which means I'm just trying to do this you have a function and you have a boxed function and you are applying the boxed function on a on box data now if either the boxed function or the box data don't exist then the result will not exist only if both the function box has a function the data box has data only then you will unwrap them you will apply them put it in the same box and send it so that is see this this understanding is not my understanding there is a very good blog post by a person called Aditya Bhargava you can actually visit ADIT.IO and he has demystified functors applicatives and monads in an awesome way and swift programmers can actually there is another post for swift programmers which is by Daniel Steinberg he has actually translated Aditya Bhargava's post to swift he actually gives a swift code there to demystify functors applicatives and monads so that was about applicatives monads are one step further I don't think we have time to discuss that only if you are interested we can catch up later and just go through it yes it is typically they say that in memoization the function has to remember the mapping which means it is local to the function it actually it's having state but that is not changing it's not changing yeah that's a good point but as long as it doesn't change it's fine yeah that's why it's possible only for pure functions yeah very rarely so I have so I basically work on the foundation libraries at the library level and there have been a couple of instances where we wanted to retain some data and in what cleaned up because of automatic reference counting it's very rare okay so okay I have time for that so have you heard of bluemix yeah so bluemix is IBM's pass platform just like Amazon has AWS and Microsoft has Azure IBM has bluemix and we want so we see that there is a huge swift developer ecosystem out there so there are 11 million developers swift developers in the world and because it's growing swift as a language has shot up from position number 28 to position number 13 in two years on the TOB index so we think that one limitation of swift is today if you are a startup and you are interested in you have a cool idea you come up with an app but for writing the server side components you have to resort to another language you can't do that in swift so people currently I think Java node I think it's node Java and Python these are very popular so companies typically they write the client the client apps in swift and the server apps in one of these languages so the question is if swift is made available on Linux why can't you write the server components as well in the same language so we have released swift on bluemix in the form of a web services framework called Kittura so now you can actually host your web services in swift inside Kittura Kittura is just like express.js node express it's inspired by express so that is the motivation because there is a huge ecosystem out there which is not able to do server side programming in swift I am not sure because Kittura got GA just last month so there is something called capture lists when you are writing a closure you can actually mention a list of what to capture and I think the object will be captured because self if you are using self inside your closure the object gets captured and it is retained if you are not using it yeah that is where we had a problem I had a problem and that is where so there is a concept of cycles in so if you have an object A and object B and A is pointing to B and B is pointing to A there is a cycle both will not get collected so in such cases I think we forge a cycle and we break it when we want to break it because as you said the self if self is not captured you are going to crash somewhere later so we have we have had instances where a local variable was not captured in the closure and some we went ahead and crashed somewhere and ideally program was expected to be captured because that's how it works on Mac so we had to hold on to it using a cycle and then break the cycle whenever we wanted to break so that is like manual memory management so that is why I am saying it's painful at times it's not like it's not as easy as the java garbage collector I don't think I it may be detecting but it's not a problem because you can intentionally maintain cycles that's what that's what I have done once yeah I think there is there is a mailing list called swift evolution and that is out of all the mailing lists that swift evolution has the maximum traffic if you subscribe to it you get around 1000 to 1500 emails per day because the language is under it's in a flux it's still under transformation because I think they are not happy with the generics I myself for this particular thing for that list cons problem I was planning to use generics but I got spiraled into the generics problem and generics are really difficult to comprehend so I think generics is something they plan to fix further in swift 4 swift 3 was a very aggressive release a lot of ABI changes so that won't be there in swift 4 I think swift 4 will have major improvements but if you are interested in the evolution of the language do subscribe to swift evolution there is a mailing list so even the currying function that I showed you the syntax of currying in swift was much easier but somehow somebody convinced that this is better than they got the syntax otherwise you could just say x int brackets y int z int that would be a curried function but now it's all about arrows because they wanted to be the arrows so do you use coco pods? I am not sure about coco pods but there is the new format called swift package manager so coco pods is a package manager apple has come up with another format for package management and that's called swift package manager SPM so there is a IBM host catalog called swift package catalog I am not sure how much of what you need is there but you can just see IBM swift package catalog you have around 1500 to 2000 packages which are present on github but I am not sure if what you need will be available here so right now I wouldn't say that it is going to be functional on its own unless somebody has worked on it because still frankly there are differences between linux and darwin so any other questions we can just catch up so yeah that's the problem objective c libraries can be used in swift only on apple platforms because they exist on apple platforms but when you come to linux they don't exist there so that's what I am involved in so there are these foundation libraries all the next step classes NS string, NS date, NS calendar these were actually inherited from objective c and currently on apple the library is actually built from objective c and you just have a swift overlay just a wrapper and then you are reaching out to it but that doesn't exist on linux so you have to have a clean room implementation of the foundation classes on linux so that is what the swift core lips foundation project does