Тёмный

Programming Paradigms - Computerphile 

Computerphile
Подписаться 2,4 млн
Просмотров 678 тыс.
50% 1

There are different styles of programming, some quite closely resemble pure mathematics. Mathematician and Computer Scientist Laurence Day compares two of them.
Note: In the Java code the delimiters within the 'for' loop should be semi-colons, not commas. Apologies for the error.
What if the Universe is a Computer Simulation: • What if the Universe i...
Sights and Sounds of Sorting with BASIC: • Programming BASIC and ...
/ computerphile
/ computer_phile
This video was filmed and edited by Sean Riley.
Computer Science at the University of Nottingham: bit.ly/nottscomputer
Computerphile is a sister project to Brady Haran's Numberphile. See the full list of Brady's video projects at: bit.ly/bradychannels

Опубликовано:

 

7 июн 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 966   
@LeodSMW
@LeodSMW 6 лет назад
This is the THIRD video introducing functional programming where the host tries to introduce it as magic where you just put an expression and it's done, and then goes "but of course that's not all there is to it!". This annoys me because you could literally have introduced Java in this with "sum(1, 10)" and then defining the method for sum. Like.. am I missing something or is this approach people like to use to introduce functional programming incredibly silly?
@Nemesis816
@Nemesis816 10 лет назад
if you ever have to sum a number of integers from 1 to z, just use the Gauss method z(z+1) / 2, arithmethic expressions are always faster than loops in computer science
@Tehsusenoh
@Tehsusenoh 10 лет назад
Aaah! You used commas in the Java for loop instead of semicolons!
@7thAttempt
@7thAttempt 8 лет назад
May also be worth stating that imperative languages such as Java in this case also afford you the freedom to recursively define the sum function - you don't have to use a loop.
@SimplyDudeFace
@SimplyDudeFace 9 лет назад
Nitpicker alert: his Java example would not compile, he is using commas to separate the parts of the for loop instead of semicolons.
@FernieCanto
@FernieCanto 10 лет назад
Come on, what programmer doesn't mix up a symbol, or forget a semicolon, or forgets the name of a method sometimes? Those trivial errors usually happen when a programmer is thinking in a higher level of abstraction, and even more when there is an IDE underlining the syntax errors during typing. Only computers are required to run flawlessly, and even they have to be fault-tolerant sometimes. So why shouldn't we?
@theodorberza9933
@theodorberza9933 9 лет назад
What he is trying to say is that in imperative languages you give instructions on how to do a process while in declarative languages you define the relations between those things.
@Computerphile
@Computerphile 10 лет назад
Name of this film changed from 'styles' to 'paradigms' to better reflect the content. >Sean
@RFDarter
@RFDarter 10 лет назад
I could write the same recursive function in Java, so what's the real difference?
@stensoft
@stensoft 8 лет назад
C++ templates are functional. Which makes them quite hard for most C++ programmers to use since the rest of C++ is (mostly) imperative.
@mrlithium69
@mrlithium69 8 лет назад
Lets see the machine code then!
@jsnadrian
@jsnadrian 10 лет назад
Brady -- I know these videos keep getting a lot of criticism, but I think that's a testament to how engaging this channel is. You've really created an amazing set of videos, here and at numberphile, sixty symbols etc.
@astroboomboy
@astroboomboy 10 лет назад
Very nice explanation. A very important part of functional programming is being able to store pointers to higher order procedures and being able to return these as a value.
@xcalibur839
@xcalibur839 10 лет назад
In the for loop, if the variable i starts at zero, there will actually be one extra iteration at the beginning where 0 is added to 0. It would be much better to initialize i at 1 for this purpose.
@Vulcapyro
@Vulcapyro 10 лет назад
It would be nice if the next explanation would be about how Java's (and others') recursion requires a finite call stack of return pointers while Haskell (and most functional languages) has guaranteed tail-call elimination and what that implies.
@TazG2000
@TazG2000 10 лет назад
"[C/C++/C#] are explicitly MS target languages" "'high level' C/C++/C# binary will never fit in registry and or memory." These comments from you are two completely different and unrelated statements, and they are both nonsense.
@qarey
@qarey 5 лет назад
I would LOVE more videos about programming paradigms!
@clays6359
@clays6359 8 лет назад
when will the video on the mentioned "dark art" be done?
@omaraymanbakr3664
@omaraymanbakr3664 2 месяца назад
10 years later and this explanation is still rock solid, thank you .:)
@kesakhan
@kesakhan 10 лет назад
this is such a well explained video, great work !
@picosdrivethru
@picosdrivethru 8 лет назад
such an awesome channel, keep it up please!
@richardhawkes
@richardhawkes 10 лет назад
I'm so hyper-aware of the high-rise-terminal (upspeak) these days, and this drove me nuts... I wish I didn't go so annoyed by these things as this was a good video!
@123456789robbie
@123456789robbie 10 лет назад
I've been programming for years, and i learned something from this video
@wwfarch
@wwfarch 10 лет назад
An in depth explanation of functional vs imperative languages is probably beyond the scope of this channel. I think loops vs recursion is a decent place to begin understanding the differences between the two types of languages.
@datastu432
@datastu432 10 лет назад
Great video! Laurence mentions that these are both "high level" languages. I'd love to see a video about how a "low level" programming language would tackle problems differently from these "high level" programming languages. Cheers!
@brodaclop
@brodaclop 9 лет назад
How times change, nowadays in Java you'd write something like IntStream.rangeClosed(1,10).reduce(0,Integer::sum);, which is suspiciously functional...ish style. Languages rarely fall into purely one category, and of course as we know, real programmers can use any language and any paradigm to write in Fortran. :)
@overcunning
@overcunning 9 лет назад
brodaclop This looks more like Javascript. Java must have more objects. And of course, factories, proxies, abstractions and all of that useless complicated stuff.
@MrCOPYPASTE
@MrCOPYPASTE 10 лет назад
One thing that the Haskell pattern matching resembled to me was the concept of terminal symbols on the definition of a grammar(and it's recursive nature). Could you do a video about parsers? Thank you.
@snugglepuff33
@snugglepuff33 4 года назад
Wow, that was really fun! So weird and different. A lot of the idiosyncrasies of Erlang and Elixir make more sense to me now.
@Squeazer
@Squeazer 8 лет назад
It's worth noting, that summing integers from 1 to N would be done by an equation: (N(N + 1))/2
@BruceRiggsGamer
@BruceRiggsGamer 9 лет назад
int total = sum(1, 10); // Java
@Bob_Burton
@Bob_Burton 10 лет назад
If you want to access the the result of sum [1..10] at more than one place in the program how do you refer to it again ? In Java you would assign the result to a variable as you have shown, but what is the functional programming equivalent ?
@reganheath
@reganheath 10 лет назад
Thanks. So if a Haskell list is (only) either an empty list, or an element and a list then in the case of a list with a single item you would say it was that item and an empty list, correct? Which is why you should always check for the empty list case. But now I'm interested, how does Haskell define sum? Is it some sort of built-in defined in something other than Haskell itself, like C or assembler?
@TheGnurgen
@TheGnurgen 8 лет назад
Using a library function for the haskell part when you defined everything for the java part is cheating. And if you were to define it in haskell i would not use lists and just do: sum 0 = 0 sum n = n + sum (n-1) and just call sum 10.
@SciJoy
@SciJoy 5 лет назад
Hello, annotations are going away. You might want to pin the "The eliminates within the 'for' loop should be semi-colons, not commas - apologies" note.
@TehMiSch
@TehMiSch 10 лет назад
Haskell is my favorite programming language! It's a shame only few people know about it, thank you Sean Riley and Mr. Day for showcasing this language on Computerphile! I would like to appeal to everyone who already knows how to program in some imperative language such as Java, C#, Python etc. to learn a functional language such as Haskell, it will IMPROVE you as a programmer in these imperative languages as you will be able to look at a problem in a different way as before.
@TensionFreeTape
@TensionFreeTape 10 лет назад
Out of interest, is this implementation specific or common across the current set of compilers/interpreters? Does the lazy evaluation model preclude tail call optimization in this sort of case?
@nylepentik2696
@nylepentik2696 10 месяцев назад
look! it’s that crypto nerd
@jagc2206
@jagc2206 7 лет назад
With the Java for loop you have ',' instead of ';'
@onwul
@onwul 10 лет назад
I did some reading on imperative and declarative, declarative resembles imperative, except everything is done with functions and input to functions usually must go through complex parsing. I get the idea of abstracting implementation and letting computer decide how to implement, but it still all boils down to imperative. On the other hand, a language to be processed by a parser or a compiler can also be seen as a declarative: its up to gcc compiler to decide how to generate assembly from the C.
@reganheath
@reganheath 10 лет назад
Thanks, makes perfect sense. The D programming language (imperative) has plenty of similar functional constructs so I am familiar with them. foldl wasn't mentioned in the video, but I am guessing you meant the steps he took are how foldl operates?
@MrCringedragon
@MrCringedragon 10 лет назад
Yikes that indent on the for loop open bracket was cringe
@havz0r
@havz0r 10 лет назад
What he is NOT saying though is that the "imperative" version is much faster than a recursive version. For high-load simulations and complex calculations, you won't see people using recursive functions just to save a few lines of code, couse they're much slower.
@ErulianADRaghath
@ErulianADRaghath 10 лет назад
I'm currently taking computer science courses in university, one thing that crop up often in discrete math course is the NP-Complete thingy. I had heard it numerous times, ask profs. and searched online, but I can't seem to understand its significance. Could you perhaps make a video explaining that?
@SpartanDemiGod
@SpartanDemiGod 2 года назад
Amazing video, simple and clear epxplaination for 2022 standards for beginners.
@Vixikats
@Vixikats 9 лет назад
It should be said that basically every modern programming language in use today uses a mixture of Imperative and Functional design. Working together is far more effective.
@yesimstuntdude
@yesimstuntdude 8 лет назад
Kaitlyn Amanda Same as how basically all modern languages intimately mix OOP and imperative programming. I think people will continue to find that functional programming paradigms are really not that different from ones already used in imperative programming, and functional style will become just another tool in the programmer's toolbox. I mean heck, if you teach someone to use immutable types, recursion, and service provider interfaces, they're already halfway to being a functional programmer without realizing it.
@Vixikats
@Vixikats 8 лет назад
Stuntddude That's the ultimate goal. Functional programming applies best in situations where efficiency is key while Imperative programming is better for being more flexible. Most programmers know how to do both of them, but it's experts who know when to use what.
@yesimstuntdude
@yesimstuntdude 8 лет назад
VoltzLiveYT I think you may be taking the idea of mixing functional and imperative too literally. Nobody is saying you should write some parts of your program in functional code and some parts in imperative code (mixing code), but you should know when to use functional concepts and paradigms alongside other concepts and paradigms (mixing styles). If you've ever deliberately designed an immutable type or written a service provider interface in an imperative language, you've already taken part in this.
@CzipperzIncorporated
@CzipperzIncorporated 8 лет назад
+Kaitlyn Amanda > Functional programming applies best in situations where efficiency is key You're full of it. Functional programming applies when _correctness_ is key, not efficiency. Copying an entire list, traversing to the end, then appending an element is much slower than just pushing a value to a vector.
@yesimstuntdude
@yesimstuntdude 8 лет назад
Chris Gregory Appending to a linked list is done at the beginning for a reason, linked lists are not the only compound data type in functional programming (that would be truly stupid), and if you have to copy an entire list just to append a value to it, it's because your code is bad and needs to be refactored.
@georgilas
@georgilas 9 лет назад
The Fibonacci sequence in Haskell: fib n = fibs !! n where fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
@frankheuser3045
@frankheuser3045 8 лет назад
Doesnt the first program terminate when i=11 ? or am i mislead ?
@exiletomars
@exiletomars 10 лет назад
So, I've always wondered, why is "i" the sort of default number for counters in for loops? Also, will you ever have a video involving the names "foo" and "bar"?
@sugarfrosted2005
@sugarfrosted2005 9 лет назад
Pretty sure you got your definition of sum wrong since it skips a special case, namely the empty sum.
@realm087
@realm087 10 лет назад
So are functional languages very high level? If you look at imperative languages they work in a way so much more similar to machine instruction when compared to the functional languages, doesn't matter how high level the imperative langguages are.
@striker865
@striker865 6 лет назад
Great video! Love the high level view
@veganaiZe
@veganaiZe 4 года назад
Forget about the commas in his `for` statement; I like the way he connects recursion with working out a simple math equation. I'd never thought about it quite exactly like that. Cognitive load lifted.
@GrEEnEyE089
@GrEEnEyE089 10 лет назад
whats the point. In java you can use a tracking variable or a recursive function to do this. why would i want to use a language like haskell then
@zakplayyy
@zakplayyy 10 лет назад
Yay! I like programming in general and its nice to see these types of videos :)
@astroboomboy
@astroboomboy 10 лет назад
That depends on how the list is implemented, the empty list is not always the base case, in C for example it is a number, and in other languages some lists have a code in the beginning and end of the list. There's just loads of different ways to make a list.
@melvicybanez5865
@melvicybanez5865 10 лет назад
The Holy FP Trinity (Functors, Monoids, and Monads) and their variants is the main reason why everyone is so scared of Haskell
@RyanShanks
@RyanShanks 10 лет назад
I may be wrong and I am not trying to attack Haskell, nor do I know much about it, but would I be correct in guessing that it is generally slower or more memory intensive given that it seems to be more heavily recursive?
@IEnumerable
@IEnumerable 10 лет назад
I was very curious how this one would turn out having suggested it as a future topic in the launch video and I must say it was very well presented. Got to the essence of the two paradigms (who cares about the picky details of the syntax). State-full step-by-step "how" programming vs. declarative expression-based "what" programming.
@XDBjoernXD
@XDBjoernXD 2 года назад
This is a nice little introduction into functional programming
@TazG2000
@TazG2000 10 лет назад
"What can't you do in any language by enhancing it or more generally adding libraries?" I think you're asking the wrong question, and missing the point. Languages are not just a means to an end. Consider languages like Coffeescript, whose *sole purpose* is to be translated to another existing language *just* so we can write in a style that is "nicer" to humans. The whole purpose of programming languages is to provide a bridge between human expression and computer instruction, not to "do" more.
@craig3.0
@craig3.0 10 лет назад
Or you could just use basic number theory and python, in which case it would be: def pyramid_sum(n): total = (n + n**2)/2 return total Or, if you didn't know that, you could do: def pyramid_sum(n): while i < n: total += i += 1 else: return total
@AvGeekLucky
@AvGeekLucky 10 лет назад
Is the magic analogy a reference to Gerald Jay Sussman's Structure and Interpretation of Computer Programs lectures?
@reganheath
@reganheath 10 лет назад
Interesting opinion. Why is the sum of an empty set not zero? Logically it seems to me that it should be. What does the built-in sum function do? I would be interested to know but I don't have the first clue how to get started with Haskell .. tho I might give it a whirl tomorrow.
@normansoetbeer1350
@normansoetbeer1350 10 лет назад
Just a bit nitpicking: technically you're adding the numbers from 0 to 10 (instead of 1 to 10) in the Java example, which means 11 iterations instead of 10. Good video anyway
@AbdulKadir-yl5vn
@AbdulKadir-yl5vn 7 лет назад
just FYI for future visitors who don't know, Java has had functional support since 2014.
@kasuha
@kasuha 10 лет назад
Pascal used to have array with arbitrary start/end points. It was rather comfortable but introduced some overhead. In C++ or Java there is no "native" support for that but you can implement an object representing such array.
@FelipeCortesS
@FelipeCortesS 10 лет назад
It would actually have an impact, and a big one. A lot of common problems in graph theory such as the traveler salesman problem are NP-complete so if NP=P we could find the best route a lot faster. Also look up about encryption methods, they usually work assuming that the inverse process (decryption) is a difficult problem, such as a NP-complete one.
@GWigWam
@GWigWam 10 лет назад
My eyes! Ahhhh it hurts so much!
@DeeWeext
@DeeWeext 8 лет назад
Haskell, by use (July, '15) 41th most used language, with popularity 0.273%.
@NikolajLepka
@NikolajLepka 10 лет назад
yeah I know I just referred to the use of semicolons, but you're right it's var for all variables and functions in javascript... as a matter of fact, you can write for loops javascript style in c# as well since c# allows for automatic type detection
@Puzzlemad
@Puzzlemad 10 лет назад
This takes me back to 1978 and using basic, pascal and fortran. You did not say why one would choose one style of language over another!
@johndoe2
@johndoe2 10 лет назад
Or "i
@bluemeeni1658
@bluemeeni1658 10 лет назад
WHAT?
@reganheath
@reganheath 10 лет назад
Thanks for the reply. I had assumed you were keeping it simple for the video, after all not all viewers are programmers nor care about this level of detail. I myself do a lot of C, C++, Java, C# and my favourite language is D. I have always wanted to do a bit of functional programming but have never found myself with a project for which it would be ideal..
@ractheworld
@ractheworld 10 лет назад
riddle me this mister ansi c, you wanna create a window in windows, how do you go about it withoug using any external library other than the standard c library???
@TazG2000
@TazG2000 10 лет назад
You clearly were talking about speed: "Even facebook realised that C is really slow and migrated do JIT compilers." Which is also wrong: they were using PHP, not C -- and again, JIT is an optimization for *interpretation* (like PHP), *not* an improvement over pre-compilation (like C). Another hint that you don't know what you're talking about is that you group "C/C++/C#" as if they're the same, which is as ignorant as grouping Java and Javascript; they have little in common besides the name.
@metime00
@metime00 10 лет назад
Join the functional traaaaaaaaaaain. Pure functional languages like Haskell can make certain assumptions about your code because of no side effects that lets the compiler gut and rearrange stuff to make it faster. The first version of Haskell came out in the early 90s, and they've been improving the compiler ever since. Performance differences are negligible, and the productivity increase from safe, testable code is a huge difference.
@blenderpanzi
@blenderpanzi 10 лет назад
Also at least in theory the JIT could optimize the code for your exact processor, including auto-verctorization etc. Also a JIT can detect if there even are derived classes of a certain class and if not it can thread all method calls on instances of that class like non-virtual function calls. And Java could be implemented so it does bound check eliminations (you can't do that easily for the STL collections). I don't know what (if any) of this the Java JIT actually does, though.
@DqwertyC
@DqwertyC 10 лет назад
In programming there are usually many different ways to write the same code, and most programmers use one because it's the more common notation. Also, especially in java, programmers start for loops at 0 because of the way arrays (lists) are indexed. If you have an array of 10 objects, they are called object 0 to object 9, so you can go through all of the objects by saying for(int i=0; i < 10; i++){ //Do stuff with the array }
@kaminarigaston
@kaminarigaston 9 лет назад
sum(1, x) = (x*x)/2 + x/2
@rdoetjes
@rdoetjes 8 лет назад
I always think in imperative problem solving methods, even with languages that have some functional approach like Python I often do it the "long way round". I guess having developed in assemblers for so long your brain gets hard wired in such away that it can't be disengaged that easy anymore. Or I just have very poor neuroplasticine behaviour ;)
@Aesculathehyena
@Aesculathehyena 10 лет назад
Wow. I ask once for programming theory, and BAM, next video is exactly that. This is why i like these ______phile channels.
@s9917912j
@s9917912j 10 лет назад
The second method actually uses recursion, the process in which a function calles itself repeatedly (a bit like a while loop in java, to a certain extent).
@plokijum
@plokijum 7 лет назад
So is Haskell same as simple recursive solutionnnn. Is Haskell a language
@annihilatorg
@annihilatorg 10 лет назад
I prefer the O(1) version of the sum 1 to N function: (1 + N)*(N/2)
@MrCOPYPASTE
@MrCOPYPASTE 10 лет назад
Yeah you were right about the empty Sum[] case, it should return 0 because its the conventional way to do it :), but I can see a couple of problems with that for example calculating the average for a list so Average[Sum[n], length n] where n is empty and that would result in 0 / 0, so isn't it better to test the length before?
@hakonmarcus
@hakonmarcus 10 лет назад
From this, I do not have any idea of how you would use functional programming to do anything else than networking simple, predefined calculations. How do you get by without variables? Is this kind of programming meant to do other things? Can you make a game with it? How would you keep things like score when you cannot store values?
@JohnCater5
@JohnCater5 9 лет назад
Upspeak! This presenter speaks in upspeak.
@piq-dg3vz
@piq-dg3vz 7 лет назад
haskell is awesome! currently learning it.
@Bodeification
@Bodeification 10 лет назад
You could, and it would have the same answer. But usually when you use a FOR loop you start from 0 and go to
@Pseudoradius
@Pseudoradius 10 лет назад
It's a little bit strange to not have sum [] = 0 in there. Especially since the non-exhaustive patterns error was mentioned and the empty list is the usual base case of lists.
@reinux
@reinux 9 лет назад
A good demonstration of one of the unfortunate reasons Haskell scares people away: we're having a discussion about mutation, when *bam*, suddenly we're talking about types and pattern matching. The Haskell community is pedagogically insane.
@Darwin226
@Darwin226 9 лет назад
I'm confused. You do realize he used pattern matching to implement the sum function, right? He didn't just mention it. It was the integral part of the solution. Just as he used the for loop to implement the iterative one. He mentioned the for loop. Did he explain it?
@reinux
@reinux 9 лет назад
The assumption of this video is that most of the audience is already aware of basic imperative programming; so I don't see why he should need to explain loops. It might have helped some people, but realistically it seems moot. Aside from pattern matching, he also uses a compiler, which is comprised of a lexer/tokenizer, a parser, at least two intermediate languages in the case of Haskell; he uses a left-to-right text layout; he uses a the decimal number system... he uses a ton of other things that are rather obscure in detail but clear in context. It's a chronic problem that a lot of CS instructors have: an inability to understand what's intuitively clear to the audience and what's not. Basic Haskell pattern matching is very intuitive. It doesn't need mentioning.
@GPCTM
@GPCTM 8 лет назад
Internet began to work. And then 'they' invented Java.
@vibe3d
@vibe3d 10 лет назад
I might have misunderstood this. Because I thought this could be just plain functions that we can write. Like the example in the video, if I just put that loop inside a function any time and supply the range when I call it, then I would have retrieved the sum in just one line of code. Or is this something entirely different? After all libraries contain functions and we're just calling them when we need them.
@RaminHonary
@RaminHonary 10 лет назад
Haskell has "static type checking," which means the entire program has a type equation. When you compile, the compiler tries to prove the consistency of your program using a theorem proving algorithm and if you have made a typing mistake anywhere in the program, the compiler catches your mistake. A similar program written in Python or Ruby cannot do this, you must run and test the program to catch the type mistakes. Java checks some types, but because of casting rules not all types are checked.
@bethelemstar4636
@bethelemstar4636 9 лет назад
its always hilarious when people post code snippets to comments, because most of them look mediocre at best
@1nt3rl1nk9
@1nt3rl1nk9 10 лет назад
What I hear in this video: imperative / Java = shit, functional / Haskell = brilliant. Without any explanation or real comparison of both approaches. This guy can not even programm a loop correctly syntactically and logically (hes looping 11 times). A good programmer first learns how to code correctly both with imperative and functional languages and then he can chose which one to use to solve his problem.
@TheDerangedGENIUS
@TheDerangedGENIUS 10 лет назад
Technically, before anything was being added to the variable "total", the "i" used as a sort of counter had 1 added to it at the beginning of the loop. So "total", which started at 0 as it should, had 1 added in the first round of the loop. He had to start with "i = 0" so the loop would start by adding 1, not 2.
@notoriouswhitemoth
@notoriouswhitemoth 10 лет назад
Maybe I'm being pedantic here, and I might be mistaken, but with the test condition being i
@MagnusSkiptonLLC
@MagnusSkiptonLLC 8 лет назад
Java looks a lot like C++.
Далее
The Most Difficult Program to Compute? - Computerphile
14:55
Arrays vs Linked Lists - Computerphile
29:57
Просмотров 491 тыс.
Object Oriented Programming is Good | Prime Reacts
31:30
4 Programming Paradigms In 40 Minutes
41:28
Просмотров 487 тыс.
Lambda Calculus - Computerphile
12:40
Просмотров 1 млн
Object Oriented Programming vs Functional Programming
18:55
Functional programming - A general introduction
11:47
Essentials: Pointer Power! - Computerphile
20:00
Просмотров 461 тыс.
Programming Loops vs Recursion - Computerphile
12:32
Просмотров 1,4 млн
The purest coding style, where bugs are near impossible
10:25
Imperative vs Declarative Programming
4:44
Просмотров 290 тыс.