F# for C# programmers - Scott Wlaschin

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I'm more interested in learning about shit like F# and Clojure in a way that doesn't assume I'm an expert on the underlying platform.

👍︎︎ 7 👤︎︎ u/ameoba 📅︎︎ Jul 06 2017 🗫︎ replies

I like how he started off saying syntactic differences were the least important difference and then spent about 10 minutes going over syntactic differences and each time touted F#'s syntax as superior without any reasons more substantial than "nobody likes semi-colons"

👍︎︎ 2 👤︎︎ u/ClysmiC 📅︎︎ Jul 05 2017 🗫︎ replies

The one problem I have is with comparing inheritance with union types. While it is true it is much clearer to know what options are possible, it becomes much harder to add new option. You have to change the code and all places where the options are pattern-matched against. Also, it is not trivial to have one of the options in external library. It would be better if he actually compared it to something of same semantic.

👍︎︎ 1 👤︎︎ u/Euphoricus 📅︎︎ Jul 06 2017 🗫︎ replies
Captions
hello everyone thanks so much for coming this is f sharp little F sharp for C sharp programmers my name is convolution I have a website F sharp F a non-profit comm which I think kind of gives away my bias so I'm a big fan of f sharp and I will try not to be too biased I'll try and present why I think this is an interesting language for you to learn but if I if I go overboard like you don't have to trust me you know you can look for yourself so the goal of this talk really it's just a demystify F sharp a bit a lot of people think that functional programming is very scary and there's monads and weird mathematical things I'm just going to try and demystify a little bit just so that you can kind of maybe get interested in investigating it obviously you can't become an expert in an hour so and I'm not going to go through this is not going to be one of those feature things where I show you all the features of the language because I think that's the kind of stuff you can learn by yourself I'm going to talk about more like the philosophy of language and how functional programming is different from audiology programming and how F sharp has a different philosophy than C sharp in terms of how you do things so is it worth the efforts to learn another new language like there's all these new languages there's rust and there's go and I was caught learn and it's like you know is it really worth it to learn a new language so this is a quote that I like a language it doesn't affect the way you think about programming is not worth knowing so for example if you know c-sharp learning Java is not going to change the way you think about programming so it's not worth learning Java I mean might be worth learning Java to get a job but it's not worth learning it to try and expand your minds like on the head I think F sharp is a language that will change the way you think about programming and so I do think it's worth putting effort in to learn it here was a conversation I saw on reddit I think some said well your f sharp is a little bit better but is it really worth the effort you know which I sympathize with that means look there's so many new things you really don't want to spend lot I'm learning something you know if you're not going to really get anything after but something with respondents with this you know learning a sharp was a big boost to my career as a c-sharp developer so it's person it doesn't either professionally there aren't that many f-sharp jobs but we're talking about personal development here were talking about learning new paradigms learning the ways of programming and he said this knowledge actually made me a better program in general so that's a good reason to learn f-sharp another way to before you put a lot of effort into something is to find somebody who has done it before so find someone you trust who has learned c-sharp and has also learned a sharp and ask them is it worth learning and if they say yes you know don't have to trust me but you know don't trust people who've never nobody just look at it and say it's horrible don't bother because you need to have it you need to have experience on both sides and only then can you make it a sensible decision so find someone like that and ask them what they think all right so some misconceptions about f-sharp I'll just clear out quickly it's developed by Microsoft Research not Microsoft proper but it became a proper maxilla product in 2010 shape with Visual Studio and now it's on a parity with c-sharp and VB and so on parity in in quotes it's open source I think it's one of the first microprocessors it's on github you can change the compiler and put a pull request in and go for it it's cross-platform it works on Linux it works on Windows on Mac it works with you know dotnet core it works with mono obviously it works really well in Visual Studio but it also works really well with other editors of Visual Studio codes has a fantastic they're sharp plug-in called ionize which I highly recommend and there's also things that you imagine them and so on really important accident friendly community when you're learning a language you don't want people to you know tell you asking stupid questions when you're beginning right you want people who are supportive so if you go to FL Paul which is the desktop software foundation there's instructions on how to download there's also instructions on how to get to the f-sharp slack channel which way there's a beginner's channel in there you can ask questions and on f-sharp on Twitter hashtag that's a great place to ask questions or to find out what's going on at their shop right so what am I going to talk about so the first thing when talked about is the differences between C sharp and F sharp when you're learning a new language you always want to kind of compare it with what you already know and that's true for anything I actually think that's a bad idea clear honest I think when you're learning something new especially if it's completely different paradigm you should actually have a like a beginner's mind and forget everything you know because it's going to interfere with your learning so ideally when you're learning language like F sharp you should forget everything you know as usual that's kind of impossible but that's would be the recommended approach because otherwise you're going to get frustrated and say well why doesn't it do this and why doesn't it do that but since you're here I am and since you are C sharp people I'm going to talk about the differences anyway so the first thing is the syntax is very different and this is probably what you see first and so what puts a lot of people off and I'll talk about that type inference is something which is very different between F sharp and C sharp to default the difference so in F sharp everything defaults to immutability for example and mutabilis is something special and it's a different philosophy about what's important when you program and then I'll talk about things which is sort of special to F sharp that C sharp doesn't have the fact that F is a functional first language the fact that F sharp has an algebraic type system and the fact that they're sharp is an interactive language you can play with it like Python or Ruby it feels like a scripting language these differences between c-sharp by the way I've ranked them from the least important and most important people really focus on the syntax that is the least important thing about language the fact that's got a different philosophy I think is more important and that but it's not obvious just by looking at the code is not obvious that they have a difficulty but I'll talk about that so let's start with a syntax because everyone this is things that people really complain about so what I'm going to do is I'll start off with a c-sharp example and I'll mutate it so I'll transform it into extra-large code so here's a mutable class and C shop it's got it's a person class it's got a name property and a birthday for pretty damn close really all right so the first thing first difference in syntax is indentation rather than curly braces and you've probably seen this here's all the curly braces and the question is do we really need them to the add value right if you look at the see shop codes I think one third of C shop code is curly braces is it really that important the indentation always already gives you everything you need to know so this is the codes with curly braces and this is the code without curly braces with indentation okay there's the curly braces there's the code of indentation now some people will say well you know is it really that harder to read without the 30 bases some people say yes it's like oh no this is like impossible to read I can't possibly understand this code I merely that's a silly thing to say okay so if you if you a couple things notice first of all you might have noticed I put equal signs that's used to start the blocks whoops and the other thing is that we can shift all the without the curly braces we actually get a vertical space back so we get a lot of vertical space compaction which is much nice which is very nice so if you're worried about white space here is a helpful Venn diagram there are people who complain about white space and there are people who've used the language with white space and the intersection is a very small intersection there there are some people who do complain and have you know who have used it but normally people who complained actually haven't done it so people complain about Python believing actually inspiring okay here's a claimant who is you know that can't get much more hacker credentials and that he said Python so he's talking about Python which is very similar to F sharp in terms of the white space the pythons using white space stopped feeling unnatural after about 20 minutes I just indented code like I would with C and it works all right and that's pretty much it just indented the way you would normally do and pretty much things work that is not the hardest part about learning a shot believe me so you know give it a go don't let this white space thing bother you how many people here know Python okay well then you've got no problem problem specials right okay here's some other syntax differences I'll just go through quickly a lot of these things are also going to be available in C at some point if they're not available now I'm sort of losing track of which features are actually making it into the C releases with first one backing fields for constructor parameters if you look at the constructor there's a name and a birthday and then there's a backing fields which will name a birthday and it's just a lot of names and that is like duplicate stuff everywhere right that's annoying let's get rid of it so in F sharp the parameters that you passed the constructor automatically become backing fields so you don't need to define them and then you can just in your property you can just return it that's saves a bit of code right there I think that's very nice the primary constructor and the class definition get merged so in c-sharp the Constructors are separate kind of methods as it were separate from the class definition in F sharp you take this constructor and you put it at the top because how often do you have more than one constructor I mean sometimes you do and in F sharp you can have secondary concerns too that's not problem but almost always why not just like make it part of the last definition like that that saves a bit of or it also saves it over to the space that's another three or four lines we've saved right there there's noise okay so this is an immutable class we've got all these gets everywhere get-get-get let's get rid of the gets okay the gets are gone that's good another thing we don't need is semicolons nobody likes semicolons right everybody hates semicolons just get rid of them now occasionally you do have two things on the same line and you can use a semicolon if you need to but you don't need to normally okay no return so in c-sharp you have a return keyword to tell you this is the return of the method whatever in F sharp you don't need it and code looks like this and the reason is that F sharp is an expression oriented language everything is an expression not a statement so an expression is something that returns something it's not just it doesn't just do something always return something's like if initiatives doing an action and a funk right everything's a funk in a pair shut there's no actions it always returns something and so it always attend something you always gonna need a return statement so you just make the last line of the block be the return so in this case the name is the last line that's what gets returns all right so you get implicit returns it's very nice all right public members okay so this is a mutable class people can't change it why make everything project so in is again it's noise like in c-sharp you spend a lot of time typing public like let's not get rid of it let's get rid of public we don't need product now an f-sharp this is a good example where the defaults are different in F sharp you can make things private if you want to even write the same havoc same accessibility modifies you can say private and internal and also the defaults are different the thought is public in seashell the default it's private all right type inference okay so in the constructor we say that the name is a string and the birthdays of dates and in the properties we say the name is a string in the birthdays a date it's like why are we duplicated this why can't the compiler figure this out why do I have to keep typing date time over over write in F sharp the compiler does forget out for us right we specify it once and then go after it's figured it out now at this point our properties are kind of getting kind of hard to know the publicist written too sparse so in F sharp you have to say that something is actually a member so that's a little bit of a clunky thing you have to say this is a member remember this dot so this is the self is the same as distance to Shabbos the self reference okay and so that in place of class remember and use the same syntax for methods there's property so this is a methods age and you calculate the age by doing something and again I don't have to return I just say that the difference mine divided by 3 6 5 that's the age so methods and properties look very similar in a shop now notice that with age I didn't have to say return to names right into the compiler forget it up so let's type annotations so in c-sharp types come before variable name it's a date time birthday string name in F sharp is give around the types come afterwards so it's birthday : day time name : stream if you've ever used pipe scripts has the same thing a lot of languages do this most modern languages now have adopt this kind of standard way of doing types so the C kind of languages have their own way of doing it but other languages do it this way different keywords okay now if you care about this is the kind of syntax difference that really if you care about this I'm sorry you know I can't help you different keywords so in F sharp C shall we use class and we use var in F sharp we use type now we use let alright and those different keywords but really that's all you have to remember it's not that hard alright now Muncy sharp does have a lot of these features when I wear this I think I've wrote this based on I know I haven't done C sharp for us I've kind of lost track of what's coming but this is an example where the constructor is merged with the class definition it's got alter properties it's got expression bodied members and so on so it does kind of look like c-sharp except for the fact you've got public and you've got the duplicated types and everything and the expression body members only work for single lines and this you know but it's the same idea I mean you know conciseness is good because tightness is really nice if you can through it alright now that was the object-oriented syntax I showed you the functional programming syntax is even simpler because all this member stuff that's kind of ugly so in front of the programming the key thing is you separate the data structures from the behavior so the functions that act on the data are separate from the data things themselves so in F sharp if I want to define a person I would define it like this so this is what we call a record type in F sharp and it kind of looks a little bit like JSON I suppose there's a name as a birthday and that's the type this is an immutable data structure with two properties there is no behavior it's just like you could think of it as a dto as well it's like a dumb object with no behavior if I want some functions that work in it i define separately i define an age function and the age function looks like that so again it's let there is one parameter which is person and there's a space between the parameters and that becomes important later on when you do things like partial application so in front of languages you can use spaces between the functional parameters notice that I didn't have to what else are they yeah I didn't have any type annotations but the fact that by passing that person then the person has a birthday it figures out that the person is a person type and it figures out there's an int return so if I look at the the woods infer the type influence we'll say this is a person - int function I don't have to specify that which is very nice so there you go that's type inference is great and so it kind of looks like if you use the Python this looks very much like Python you're not specifying any types anywhere just kind of writing code and you know but unlike pythons are strictly type so you'll get a compile error if you make mistake so as I said syntax is not the most important thing it's never the most important thing about a program language but okay I'm going to make an exception originally we had like 20 line throwing on lines of code now we've got five lines of code if we take those two properties and we're fine if you compare C sharp and F sharp code bases at words that actually pretty much the same code when we win we'll find that F sharp code in general is about three times less you know one third of my check shell code C shell code because of the vertical compression because the letter braces the lack of null checking the fact they don't have constructors and stuff there's just a lot less codes and that's kind of I think that's kind of important in those syntax is not that important I think the fact you can see three times more on your screen it's like getting a super large monitor so that's nice and you don't have to write 1/3 as much code that's nice too so that's not like I say syntax is not that form but I think concise is important and I think c-sharp and sometimes be a little verbose you know but that's not the I mean I wouldn't say that's not the only reason to using language so just let you know as I've been more important reasons type inference okay so that's the syntax stuff type inference here's a function do something and it's got some parameters and F N and X and let's say we're going to add one to X and we're going to pass it into this F so f is obviously some sort of function and then the output of that function is a Y and then we're going to take Y we're going to add it to hello so what can I haven't specified anything in the parameters right so can the compiler figure out what's going on and the answer is yes it does and the way it does it like this first of all it says that X has to be an int because anything you add an int has to be then F shops really strict there's no kind of coercion between types so you can't add a float to an int and you can't add an n64 to the Infinity they're all different so this knows that X has to be an int and then it also knows because you're passing into FS memory function now what about Y Y has to be a string for the same reason if you want to add something to another string Y has to be a string so now if we look at F we know the input F is an int and the output of F is a string so it's an interesting function and so finally this is the inferred type okay the first parameter F is a function which takes the internet registry the second parameter is an integer and the return type the very last line is a string because that's hello positive so the type emphases works like this it continued quite a lot of stuff occasionally you need to annotate types but many many cases you can just write code like this and it just works because that's all very good but is it really how useful that really I mean it's kind of save some typing let me show you a more complex example okay this is the group by extension method from the link and I challenge you to scan this and figure out what exactly it does there's a lot of noise here sometimes you can't even find the name of the method because it's buried under Wooster I mean this is nice Dino it's nice to know but there's a lot of noise and if you're writing your own functions you're gonna have to figure out what all these types are yourself and annotate them properly in F sharp the code looks like this okay almost always the compiler will figure out all this stuff for you which is kind of cool so the benefit of type inference is obviously less typing but more importantly less noise you can really focus on the logic of the code and not worry about the kind of types getting away again if anyone who's used a dynamic language like Python or Ruby you don't really need to see all the types every single time in visual studio and in vs code you can actually hover over the thing that will tell you what the types are and there's a code lens thing I mean there's lots of things that will tell you what the types are without having to type them explicitly alright different defaults so the different defaults in F sharp it's readable by default mutability is a special case everything is non null by default and if you want null ability that's a special case everything the F sharp record types and stuff are structural yet structural equality by default and reference equality is a special case or the classes and stuff you get reference equality so structural quality means that if all the properties are the same then the two things are the same I'm sure you've written you know in equals and get hash codes to do that a million times right and then everything must be initialized that's a big difference so let's start with immutability so there's a value in F sharp x equals one now in F sharp the assignment operator is not equals the assignment operators the backwards error like that it's a different thing altogether so you can't assignment an equality or not going to get mixed up so we're going to assign two to X and if we try and do it the compiler is going to complain it says it's not me at all okay now if I do want a mutable value I have to use the mutable keyword and then when I assign it is happy so this is saying that mutability something have to ask for it's not something happens by default because you have to ask for it and because it's so explicit you tend to use it less you know it's like we tend to vote because we're lazy right we tend to use whatever the easiest if things in c-sharp we've been we can create read only class and seashell bins kind of pain so attempts not bother so much we everything to be rid of all you know we tend not to do it this way in F sharp tips that opposite everything is immutable by default and so if you're lazy you just follow the flow and make everything immutable and very occasionally you need things to be readable what about null ability so here's our person type if I do this so I'm going to say this is X is a person and I'm going to assign it to be null I get a compile time error person doesn't have Nile as a value okay this is very different from C shop where you can assign null to most classes if I do want to assign not at all so I have to do like this okay I have to say allow null literal attributes on top and I had to use a special class and so on it's like painful right and we need does work if I do this but because it's much more painful you're really never going to do it the only reason you might want to do is to be back fully compatible with something you know but I never going to use this in your code so you never going to Mike you can pretty much rely that all your classes in a shell are never going to be involved that's nice when you eliminate no checking if you have a right defensive code in your constructor you know if the parameter is null throw an exception or whatever you never see that kind of code in a shell because nothing it's nothing so you can guarantee that nothing's none okay structural equality so here's our person time again now let's say that we have this crazy rule that if someone has the same name and they have the same birthday they're the same person all right not a very good rule but I've seen that actually done in practice so here's a Alice version one Alice version two both these things have the same name they have the same birthday the question is are they equal is alice version one the same as alice version two and the answer is yes in F sharp that is true you do not have to override get hashcode and you do not have to override equals to get this this is the default behavior and that's the brake relief to me because I hate writing equals and I always get it wrong I worry that there might be some special case when two things are known I haven't checked it properly say I can never remember to do it right I probably have bugs in my code and the same thing with get hash code hate writing it right so you don't have to write that's one one big relief there okay everything has to be initialized okay here's our person again okay so in c-sharp you can say here's a variable here's a backing fielders or something and it's just going to be a person now in c-sharp that can be set to null the default value for a class is not F sharp that's Noah okay you can't there is no default value for anything null is certainly not a problem only fit it's not an amiable thing so you always have to initialize it to be something so you never have an uninitialized variable in Excel and if you partially initialize it there so you set the name but you forget to set the birthday that's also an error every single property is required when you initialize it so if you add a new property all your code or break until you fixed it which is probably good I think I don't know you know you never have this thing we've added a new property in some deeper gets initializer probably because you've got constructor which is backwards compatible and yeah that's never gonna happen F sharp which it is so you can trust a lot of is to do with trust you can trust that things have been properly initialized so you tend to not write defensive codes in their shop you don't have to check for null you don't have to check is it initializes a valid objects all that stuff tends to disappear so that's another reason why the code is shorter because there's just a lot less defensive programming all right so here's an is that what I think is the most important thing which is the different philosophy so she C sharp obviously is derived from c-like languages obviously it doesn't have pointers and you know stuff like that but it's got the imperative model you have for loops you have mutability and so on and so forth f-sharp is a cousin of ML which is a language designed in the 1970s pretty much around the same time as C and that M L stands for meta language and it was originally designed to proving things okay so it wasn't really designed to be a kind of useful enterprise programming language and that means there's a different philosophy and so let's look at example of a philosophical difference and let's talk about predictable code so what I mean by predictable code is can you understand the code in front of you just by looking at it okay you're not allowed to look at the documentation you're not allowed to look at rest the code base not allowed to look at the implementation I think just by looking at the code in front of you can you tell what it does right and if you can that's great because that's one this makes understanding the field much easier so here's some code x equals one do something with x and y equals hello plus X so the question is what is y well in c-sharp this wouldn't work but if I told you the answer is hello world will that give you a clue now the answers you can't tell this is a trick question actually because this is actually JavaScript okay it's not sous-chef at all this do something function in JavaScript changes what X is from us into a string and it does it silently so that when I come back later and I use it it's now a string and Y is now HelloWorld okay this is horrible this is horrible this is like code you can't there's an example of why you can't you know trust Jessica in c-sharp that could never happen because you got static typing you can't change the type of something you know magically behind the scenes so this is an example of c-sharp being more predictable Angelika if you look at the seashell code you can you know the fact they can't compile just by looking at the code you don't have to you know look at the implementation of do something to figure out that it's not going to compile so this is good this is the kind of thing we want so let's take this extend this and look at some other things so let's say we're trying to make a predictable language rule number one you're not allowed to change the type of a variable once you define it that's a very good rule okay let's look at another example to customers and see sharps they have the same ID in the same name are the customers equal well you can't tell because it depends on whether the customer class has over equals or not get hashcode and equals monster you can't tell because behavior in oh in the object-oriented world you're not supposed to know about the behavior on objects so they'll give something to be opaque right so you can't tell I think to make the code a predictable language if they have the same values they should be equal okay now that I'm not saying that force to be true but this is on this particular set of guidelines making things predictable it makes life much more predictable okay here is a customer and here is an order and they both happen to have the same properties and the same values in those properties so the next question is the customer equal to the order all right can you tell well you might say well it depends on how they've overridden equality and so on it's like no that's the wrong answer this is probably a bug like if you've accidentally compared the two things by mistake why would you ever compare a customer to an order this locus of bugs in your code you've you've typed the wrong thing so ideally your compiler would say you're not allowed this is a compile error you're not allowed to compare two different things right so for predictability point of view that should be compile time error okay how about another one let's say you create a customer then you say the customer has an address and the address has a country and you what is the value of that what is the address country well what's going to happen are you going to get a null reference so you're going to get who knows maybe maybe the customers initialized address to something valid I don't know I can't tell all right because the constructor has no parameters so you know and we can probably assume that it's probably been left it's not but we can't tell and you know if the customer if the dress is not required if it's an optional thing then we should make it a special optional type don't just set it so none so here's another one whoops always initialize objects for valid state we want the compiler to enforce this okay that way we guarantee when we look at an object we know that it's in a valid state we never have to test with us no we never have to test where the address has been set and so on and if it's not a valid state as a component okay here's another one we've got a set of we have a customer we add it to a set and then we do something with the customer we don't know what happened to that customer a next question is that customer still in the set of customers true or false and the answer is we don't know because the process customer one you could have mutated the customer and you might change its hash code and when you look it up again it's in a different place so that you can try knowing okay that's the problem with mutable stuff now if you have something where as an immutable customer and you do something if the process customer changes it it's going to have to return a new thing it's going to be like they're an ER in your in your face that it's returned a new changed version of the customer and if it hasn't changed the customer then it's not going to turn anything but you know if it doesn't return anything it can't possibly acclaims the customer so immutability is great there and in this case the original customers never changed so if the hash code can't have changed is always going to be existing an asset so you can rely the things are going to work the immutability is very useful in terms of knowing and trusting that your code is not going to break you know so here's all these things we talked about can't change the title of that one more so yeah objects inflation should be immutable it makes life really easy now these guidelines is about immutability about predictability now you might say well I need mutability stuff for performance I know I'm entering an array because I've got stuff it's like yes the guidelines for good performance are different from the guidelines for predictability and they they collide sometimes performance is more important than predictability sometimes critical to do it is more important than performance and you just have to choose but if you're if you're going for predictable immutability is the best thing to go for one more so let's say we have some sort of customer database and we're going to get a customer using this ID okay so what is the output what is the ID we get return this customer type value what's the idea of that customer well what happens if the customer is missing okay let's say you can't find in the database what is that customer is the customer meal know or is it even to throw an exception or what I don't know can't tell if the customers null if you're going to use null as the dimension then that's the rest of the code is on a break if you're going to throw an exception there's a permission I mean I'm going to have to look at the documentation or something to figure out right what you really want to do is do something this return something which is the customer or the error and now you can handle two different cases if there's a customer there you can get it and if it's an error there you can get it but by making it a special type called customer or error you've made it explicit that this thing might work might not work and if it doesn't work here's the here's the you know the error case you don't have to like figure out the documentation of regret is it normal non okay so these are over the rules no missing data no nulls okay so trying to document things using the type system so f-sharp aims to be a particular anguish like this you know you're not allowed to change the type of variable objects with the same values are equal by default objects of different types can't be compared obvious have to be initialized something objects are generally immutable missing data errors I made explicit by using special types if you use a null let's consider code smell and f-sharp if you throw exceptions for control flow obviously sometimes you throw exceptions which you just can't handle something that's fine but if you're trying to throw an exception a far not found exception that's the control flow you shouldn't throw exceptions for that so in F sharp you tend not to do that so f is not perfect obviously there's backdoors and you can't always dress it but you can see that the kind of conventions lean in the certain direction the philosophy behind what you think is good code and bad code like in c-sharp null is not necessarily a kernel in F sharp is a state in a personal so that's kind of a philosophical difference between the two languages all right so that's the end of the differences now let's look at some of the things which is kind of unique to F sharp and the first thing but F sharp is a functional first language now what do I mean by that F sharp is a hybrid language you can do our programming and you can do functional programming but it leans towards functional program we tend to do the functional stuff first that's all kind of go to if we can use object programming in the you know if there's a particular need for it in a certain situation but generally prefer to use functional programming if we can so let me just quickly four people are not familiar with functional programming I'm just going to quickly give you some things about front of the programming so functional programming functions are the most important things in functional programming they're the building blocks for everything the way that you combine functions is composition so like Lego so in an object-oriented language you make classes that contain other classes and you build bigger classes and then in a functional program languages create functions out of smaller functions and you compose functions to make bigger things that's how it works and parameterization is really important in front of the programming so in if you want to share codes you know you don't want to repeat yourself and you won't have share code you tend to use parameters rather than base classes rather than using heritance or something parameterization is that way of doing it so in functional programming functions are things and I think of like a little bit of railway track with a tunnel on top there's an input there's an output like the inputs at Apple and the output is a banana so you see Apple Aero banana so here is a in F sharp you like the toad like this to define a normal thing you say let x equals 1 and to define a function say let ads because this and that gives you a bit of railway track notice that in F sharp we use the same keywords less to define normal values simple values and also to define functions that's not a coincidence because in F sharp functions are treated like things okay so the difference being a thing like an integer and a thing like a function is not that big a difference so it's a standalone thing a function and because it's a thing it can be used as inputs and outputs to other functions so here's our where we track here's an input and the output could be a function for example because it's a thing or you could have a function as the input to a function or you could have a function with an input now but then there's a an extra parameter which is another function which is that can controls how the function works think strategy pan for example strategy practice exactly the same thing so this is the basic model for how you do stuff in functional programming and that's it really that's pretty much all you need to know you can see that it gets quite complicated functions that return functions that return functions can get quite complicated but the concepts are basically straightforward so let's love the composition quickly so composition you have two functions and you want to glue them together an F sharp that's the double angle bracket and you glue them together now you get a new function now what's interesting is that you can't tell this new function was built from smaller functions right the fact that how it was built is now hidden from you so for example whether the banana go right in the low-level codes you care about bananas but when you get to the high level code bananas aren't important so you've now abstracted away that the bananas are ever in thorns alright so that's how you can't do abstraction in F sharp let's say we have some functions if I want to compose them I use the double angle bracket again so here's a new function that just the add function glued together with a double function and I can just call this is a new function I can just call it let's say five add one at six double it is twelve sets the answer right so it's just basically glued two little functions together to make a bigger function and I can do that with like three functions same kind of thing all right so as you can see this it's really easy in a shot to do this like you can see the language is designed to make this easy let's look at it in c-sharp see how in citizen C shop so in c-sharp here are our functions and first of all we don't get the type inference so we have to define what the types of the functions are and if you want to compose functions together we have to have a special extension method called compose and that extension method is not built into c-sharp so we have to write our own it's not that hard to write but you know you could write code like this but nobody would understand it unless you were functional programmer already if we were you already knew functional program this would be fine but I wouldn't like if I was in a c-sharp codebase I wouldn't like this kind of code because no wonder that most of my colleagues wouldn't be able to sell my program so it's just not natural in c-sharp c-sharp is not a functional first language another thing you do an f-sharp a lot is another kind of composition is piping so let's say you you know you have a function you add 1 to 5 and then you want to double it and then you want to square that in typical languages you have these nested parentheses and they get deeper and deeper and deeper and you can lose track these nested function calls and get quite confusing like you lose their where's like where does it start after kind of go down another third of way I think about is as a pipeline so you started with 5 and you feed that into the add function the output of 6 you take the 6 you feed it into the double function you take that and you feed into the square function so this pipeline oriented model and I think it's just a lot easier understand same same concept the same end result but I just didn't kind of conceptual when you think about it and the F sharp you have the same pipeline so if you use the UNIX the cool pipe right piping things on the honor and the grand line same kind of thing except of the pipe character in F sharp here's a vertical bar with a angle bracket so in F sharp you tend to see the bottom kind of code rather than the top kind of code the top kind of code is kind of ugly the bottom kind of code is very much more common and you can do the same thing in C sharp define some functions define a pipe helper function but again I would never write code like this in some shop so you can do it so this is the differences it's not that you can't I mean it's not that you can do it it's something they've shot you can't do in c-sharp and vice versa I mean honestly theory they're equivalent but in practice it's you know you tend to do things in a certain way because the language makes it easy the language c-sharp does not make it easy to do this kind of functional programming stuff and in F sharp makes it easy okay here's another one prioritize all the things so here is a function that prints the numbers one to ten all right this is a show up code and the first thing we do if we're inexperienced programs so you know why have you hard-coded ten why don't if you want to print one to eleven or two to seventeen you don't have codes the numbers pass the numbers in as a parameter right and then so it's second nature to us to prioritize this kind of stuff don't hard-code something when you can pass it in as a parameter like second nature now if you have functional programmer you say well you've hard-coded the behavior as well it's like well weapons if I don't want to print it what happens if I want to you know do something else of it I don't hard-code the behavior parameterizing so a functional programmer would parameterize the action that you take as well you just make another parameter and this is what you do with each thing in the list and now what we've made is we actually made a much more generic designed because we've decoupled the action the lists are the action and the looping they're all now to put you suffer so we actually got a more decoupled design fact this is no longer just printing the list it could be doing anything within us this iterating over this and doing something it's easy in F sharp because you can just stick the proud to right there it's really easy to do you just type it and you don't have to worry about what type it is I'd what is the type of action I don't know the compiler will flip around for me so it's very easy to do which is why people do it again it's just a natural behavior and they're sharp to do this kind of thing let's look at a more complex example let's look at them say that we have a product and a thumb and obviously there's some duplicate code here and don't repeat yourself right so what can we do to not repeat ourselves so what we're going to do is we want to notice that some of the code is common the looping through the list is common code that the initial value is different and the action that we take each time through the loop is different right so we have some stuff which is in common and some stuff which are different so what we naturally do is you parameterize the stuff that's different and keep the common code the same so here's how to look at F sharp the function that does it is called fold we have some parameters we have the action parameter and the initial value parameter and then the list of things so we're going to say the total so far is the initial and initialize it to the initial value I'm going to be using mutable here just to make it look like the C sharp there are other ways of doing it now sharp but just to make it look the same if each item the lists we're going to run the action on the total so far and the new item in the listen that's going to give us another total and at the end after we've gone through every item we have the final total and that becomes the return value so there you can see that we've got the common codes we've got the initial value in for the prime time action so this is how you'd write that code in in F sharp and once you've done that you can go back and you can write the product and the sum in this way using this list fold section and there's the initial value and there's the action what's cool about doing this way is that we've got a lot more focus now on what's the difference in the original c-sharp code you know a lot of the code was the common code and it's hard to see what was special about each case by making it parameterised is very clear what the difference in the initial value is and it's also very clear what the difference in the action huge sleepers and the actual loop logic is you know something we don't care about if you're doing link this is the same as a link aggregate this stop fold is the same as a link aggregate and in their shot there's lots and lots of tection functions like this and one of the challenges when you're learning f sharp is to memorize what all these functions are cuz it's like 100 of them and they're all slightly different definitely worth spending some time figuring out what they will do alright so there's a lot of topics talked about functional design patterns I have he'll talk about functional design patterns if you go to my website FP patterns or just google for functional design patterns and I think you'll come across the talk alright another thing about F sharp is this algebraic type system so f sharp types are different from classes okay a type is not a class a type is more like this set and it's something very important to kind of get into your heads so what is a type so if we have these functions there's a set of inputs in there set of outputs right so a type is just the name that you give to a set of things there can be users input so you have all these integers we're going to give it a name we're going to call it an integer that's the name of the set all these strings were going to give it a name we call its string so the string type is just a list of every possible string in the world right if you have a person type it so it's just a set of all the possible people in the world if you have a food type this is over all possible fruit in the world all right since it's just a set it can be anything so you can have a set of functions so this is the set of all functions that work on fruits so this is each of these functions it has a fruit input and a flute output so it's a fruit - fruit function this is the set of all fruit - fruit functions so we call that the fruit - fruit type so anything can be anything of your type now because the types are just data because it's just a set there's no behavior it's really easy to glue them together and you can use composition just like you can for functions and that's why it's called an algebraic items because just like an algebra you can add things and multiply things in the F chart type system you can add types and not types so again we're going to use the Lego analogy now there's two ways of gluing types together in a shop you can end them and even or them okay and I'll explain what that means in a second so that's basically two different things so the end what does it mean to and so let's say you have fruit salad and a fruit salad is one each of an apple and a banana and a cherry okay now that is the common this kind of anding together a name is a first name and a last name and address is a street and a city and a postcode riddle this is what you used to in all languages have a data structure like this okay and an f-sharp could write like this okay so a fruit salad as well as an Apple property and a banana property in a cherry popped all right that's something you're very familiar with the other way is something that you probably won't be familiar with if unless you've had experience with functional languages often you will have a choice of things as snack is a apple or banana or a cherry it's a choice one of these things not all of them but one of them only and this is the kind of type that's not available in c-sharp and in extra up is called a discriminated Union type or a some type and this case you use the vertical bar so this is an apple or it's a banana or it's a cherry okay these are really really useful types one of the things I miss in C shop that's in their shop is like even forget about the functional program side this is fantastic and I will see why in a minute so let's look at an example of how you might do this so let's say you have a business requirement that you're going to accept card payment payments for an e-commerce and you can all right you know you can accept cash you can accept a check or you can scepter credit card all right so if there's cash there's no other information if there's a check you need a check number if it's a credit card you need a credit card type and a card number and so on so how would you implement this these requirements well if you you know c-sharp programmer you'd probably say well okay I'm going to start with some sort of base class or some interface or something and then I'm going to create a cash class that inherits from an al-qaeda check class with some extra data then hits and I'll create a card class with Mexico later than house from and so on so that's probably the some of the object oriented we're using inheritance now that's fine except that you can out four different files probably because you wouldn't put them all in the same file it's kind of contends a little bit ugly let's look at how f-sharp is very different so in F sharp you build the system by composing smaller types so we're starting for some simple primitive types are going to say a check number is an int and a card numbers of string so those are just primitives and then we're going to say that a card type is a Visa or a MasterCard that's an all type a choice type and then we're going to say a credit card is a card type and card number and that multiplication that's the pair that's the F sharp symbol for tuple as a pair of those things and now our payment method is a choice it's either cash or it's a cheque or it's a card and if it's a cheque there's some extra information and if there's a card there's some extra information and then we'll say okay the payment amount is another primitive type and then the currency is a choice between euros and dollars and then finally our top level payment is going to be an amount plus of currency class or method so there's an end so what we've done here is we've built a complex type in 20 lines of codes without writing any real coach this is a great way of doing kind of design okay you can get this good there's on one piece of paper is really nice so you can see it's a very different way of thinking about how you construct your domain model so this is one of the principles in F sharp used types as kind of executable documentation so if I showed you this this is f sharp code can you guess what domain this is I just by looking at the code even if you want an F sharp expert can you guess what this is I think you can even say well it's something to do with playing cards right and you can see that the suit there's a choice between a club and a diamond in the heart and whatever card is a pair a suit in a rank and a hand as a mister cards and deckers mister cards and a player as a name and and so I'm settled those are the nouns you can also document verbs so think to deal is a function and you start off with the deck that's your input the output is a new deck because the decks immutable so now I'm going to have a deck with missing a card and you're also going to have a card on the table so that's the output similarly when you pick up a card off the table the input is the is your hand plus the card on the table that's the input and the output you have a new hand and the card on tables now disappears because everything's immutable so you've got a different hand it's not you haven't mutated your hand you have a different hand with this extra card in it it fits on one screen so it's documentation it's also code this is compatible code is very nice here's another example of executable presentation if I show you this and I say what payment methods are accepted it's like really obvious right now with the arrow thing I've have to look in four different files I'd have to find all the things that inherit it's not really obvious just by looking at the code what payment methods are accepted I have to look at some documentation probably so I think this is really nice if you're trying to do like domain design something so another big topic I don't really have enough time I have a whole talk on domain garden design and designing the types and I am doing that talk this afternoon I also have a book coming out soon it's an early access right now it should be out in a couple of months so there's basically this topic like interactivity the last thing and I've got a few minutes left before I forget I just want to say that don't forget if you're interested in F sharp or any other function language there is a lab where anyone can show up and you can ask questions of the functional tract people so the functional prac I think is in this room all day and all tomorrow and you know if you're interested in programming just stay in this room and if you've got questions like they come to the functional lab and you can ask questions of people and we can do curve demos and stuff and there's something else I was going to say right interactivity so I've got a few minutes left and let me just show you some enter to by the way f-sharp fun is a few words in this job I just want to point that out I'm not trying to imply anything just purely purely by coincidence one thing about if I think it is a fun language I mean I don't think anyone says I love programming so job is fantastic your jelly no Java I think the thing about Franklin language is because it's concise it feels like a scripting language so you feel like you can select type stuff and it kind of works which is very nice so I am going to switch to visual studio if you can see that okay yeah so let me show you some code so here's a here's some real F sharp code so this is in F sharp you have the this is f sharp scripts but next shot you can actually like highlight codes and you can run it interactively I'm going to say execute in interactive now what happens is it pops up down here at the bottom modem if you can see that so basically it's one this piece of code just this one snippet of code and I can so I can interactively play with this pen well that's interesting no wonder what happens there and I can say you know add one to five and it's like it doesn't have to compile I can just like one it's both enter in that six so that's very nice so here's a here's a classic thing think of a number this is a game think of a number add 1 to it square it subtract 1 divided by than we first thought of subtract the number you first thought of and the answer is 2 okay so this is kind of a children's thing now an F sharp this is how you'd write it you see if you add one square it subtract one divided by the number you first thought of subtract by normal you first of all Tov okay there's our functions and then we just pipe them so you start with a number you've first thought of you pipe it into add 1 you pipe it into square it you can pipe that into know so this code looks very much like the requirements this Python model is great for this kind of thing a jig it kind of looks like your codes and what I can do is then like run it and see and I highlight everything and there it is notice that I didn't specify what kind of function it was its figured out that you pass the integer and it returns an integer it's nice if we think of a number if I pass in ten hey the answer is two if I pass in eleven the answers - and you know it because it's so easy and let's see log it and then I'm going to turn so here I'm going to use a semicolon - what's the problem oh I need to pass the X in there all right and then answer this is how easy you can like I want you know it didn't tell me what the region number was so I'm going to do this I'm just going to stick it in the pipeline and that mutineer helper function that logs the input as that so I can play with it interactively and go down here highlight it all again and try it again and now this time it says a is because I've got a bug in my code because I didn't say this an integer there we go so the nice thing about interacting I didn't have to write a unit test I could like play with it and find a bug all right so by playing with I already found a bug and it's like it took me seconds to fix it so this feels like doing Python or JavaScript doesn't even like JavaScript but certainly feels like Python to me very nice very easy to work with I'll do one more quickly and I got about a minute left so this is a Roman digit converter so I'm going to define a type Roman digit so I'm going to use a choice and I'm going to say okay a Roman number is a list of digits and to convert a digit to an internal and say well if it's an AI that's a one over severe to five and so on and then I'm just going to not going to really go through the code but I'm just showing that you think this is what their shots that looks like I'm going to map it and then one of summits so here's my digits and the answer 16 if I change the digits to be XX then the answer is now 26 and I put another one in here and it's now 27 so you can see it's really easy to play around with this is one of the legacies but it's a fun language to work with right so that's the demo likes it feels next ripping owns a lot of fun to work with and that is it thanks very much the slides and the video will be up on my website in a couple of weeks under C sharp if you want F sharp insulting we have a consultant communication works most importantly if you want to know more about F sharp F sharp org is the workplace should go so thanks very much and don't forget to fill in the thing when you go out thanks so much
Info
Channel: NDC Conferences
Views: 51,467
Rating: 4.9007936 out of 5
Keywords: NDC, NDC Oslo, Scott Wlaschin, .NET, Functional Programming, F#
Id: KPa8Yw_Navk
Channel Id: undefined
Length: 60min 0sec (3600 seconds)
Published: Wed Jul 05 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.