Related
I've done some research about Lua programming but I'm still confused about under which paradigm it can work.
In some walkthroughs, I've found that Lua is not made for Object-Oriented Programming. But they are other people that says it can work too for OOP. So, I'm looking in which programming paradigms it can work the best.
Lua is a "do what you want to" programming language. It doesn't pick paradigms; it is a bag of useful features that give you the freedom to use whatever paradigm that you need. It doesn't have functional language features, but it does feature functions as first-class objects and proper lexical scoping. So you can use it functionally if you so desire. It doesn't have "classes" or other such prototypes, but it does feature ways to encapsulate data and special syntax for calling a function with a "this" object. So you can use it to build objects.
Lua does not dictate what you do with it; that's up to you. It provides low-level tools that allow you to easily build whatever paradigm you wish.
Lua is an imperative language; so it is not ideal for functional programming.
Left by itself, Lua is a procedural language. However, given the simplicity of its data structures (it just has one: the table) it's very easy to add a "layer" on top of it and make it an object oriented language. The most basic inheritance rule can be achieved in as little as 10 lines of code. There are several libraries out there that provide a more refined experience though. My library, middleclass, is 140 LOC in total.
Another great way of using Lua is as an scripting language. It's small, fast, uses only standard C stuff, and it's standard lib is tiny. On the other hand, it doesn't come with "batteries included" like java does.
Finally, I find it very useful as a data notation language; you can express raw data in a format very similar to JSON.
In general, I think that Lua feels very close to javascript.
I've been reading lots on functional languages and would like to maybe play with re-writing some parts of my application in F#. Is it better to design from the outside in or the inside out?
One of the influental works on the subject of FP Why Functional Programming Matters by John Hughes can be considered as a direct answer:
Our ability to decompose
a problem into parts depends directly on our ability to glue solutions
together. To support modular programming, a language must provide good
glue. Functional programming languages provide two new kinds of glue —
higher-order functions and lazy evaluation. Using these glues one can modularize
programs in new and useful ways, and we’ve shown several examples of this.
Smaller and more general modules can be reused more widely, easing subsequent
programming. This explains why functional programs are so much smaller and
easier to write than conventional ones. It also provides a target for functional
programmers to aim at. If any part of a program is messy or complicated, the
programmer should attempt to modularize it and to generalize the parts. He or
she should expect to use higher-order functions and lazy evaluation as the tools
for doing this.
I would also recommend looking at contemporary interview with John Hughes in InfoQ.
One article that really helped me come to terms with functional programming is this one:
http://prog21.dadgum.com/23.html
It is a tutorial for how to create a Pac-Man clone using functional-programming techniques. I don't even recognize the language he used (it might have been Erlang,) but the explanation helped me understand the correct mindset which I used when rewriting one of my programs in Scheme.
I'm not an expert at all on this subject, but here is a link to an article on this subject, by 'our' very own Brian:
How does functional programming affect the structure of your code?
And some questions from SO & Programmers (where - incidentally - I suspect this question would be a better fit)
Real world pitfalls of introducing F# into a large codebase and engineering team
How to organize F# source of large project (>300 classes) in Visual Studio?
Not sure I understand what is meant by "inside out" / "outside in", but FP is most useful "in the small" -- at the function level. OO is probably still the best way to organize projects in the large. It's easiest to deal with objects that correlate with your business domain.
I guess by outside in you mean top to bottom approach and by inside out you mean from bottom to top. If this is what you mean than FP is more suited towards bottom up approach i.e inside out.
While designing FP programs think about solving the problem using:
Data Structure : What all data your application needs to handle and
which data structure is most suitable to represent that data.
Function : A function does one thing (and do it correctly).
Composition : Create new functions which achieve their goals by composing other functions using technique like higher order functions and compositions.
Other more advance and abstract FP techniques like Monads etc.
So basically you start from bottom, for each atomic problem you write a function and then as you move upward in the design you use these atomic function to create functions at higher level using composition.
Remember always think of solving problem using abstractions and composition of those abstraction rather than thinking sequentially as you would do in a imperative programming.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I recently took a look at Factor, and the idea of having a language based around the concept of a stack is very interesting. (This was my first encounter with a stack-oriented language.) However, I don't see any practical advantages of such a paradigm. To me, it just seems like more trouble than it's worth. Why would I use a stack-oriented language such as Factor or Forth?
I'm ignoring factors (excuse the pun) such as the availability of tools and libraries. I'm asking only about the language paradigm itself.
Stack orientation is an implementation detail. For example, Joy can be implemented using rewriting - no stack. This is why some prefer to say "concatenative" or "compositional". With quotations and combinators you can code without thinking about the stack.
Expressing yourself with pure composition and without locals or named arguments is the key. It's extremely succinct with no syntactic overhead. Composition makes it very easy to factor out redundancy and to "algebraically" manipulate your code; boiling it down to its essence.
Once you've fallen in love with this point-free style you'll become annoyed by even the slightest composition syntax in other languages (even if just a dot). In concatenative languages, white space is the composition operator.
I'm not sure whether this will quite answer your question, but you'll find that Factor describes itself as a concatenative language first and foremost. It just happens also to have a stack-based execution model. Unfortunately, I can't find Slava's blog post(? or maybe on the Factor Wiki?) talking about this.
The concatenative model basically means that you pass around "hunks of code" (well, that's how you program anyway) and composition looks like concatenation. Operations like currying are also easy to express in a stack-based language since you just pre-compose with code that adds one thing to the stack. In Factor, at least, this is expressed via a word called curry. This makes it much easier to do higher order programming, and mapping over sequences eventually becomes the "obvious way to do it". I came from Lisp and was amazed going back after programming in Factor for a bit that you couldn't do "obvious things" like bi in Lisp. It really does change how you express things.
Incidentally, it's wise not to get too hung up on the whole stack manipulation thing. Using the locals vocabulary (described here: http://docs.factorcode.org/content/article-locals.html), you don't have to worry about shuffling things around. Often there's a neat way to express things without local variables, but I tend to do that second.
One of the important reasons stack-based languages are being developed is because the minimalism of their semantics allows straightforward interpreter and compiler implementation, as well as optimization.
So, one of the practical advantage of such paradigm is that it allows enthusiast people to easily build more complex things and paradigms on top of them.
The Scheme programming language is another example of that: minimalist syntax and semantics, straightforward implementation, and lots of fun!
[EDITED] We already have good answers and I know nothing about the Factor language. However, the favouring of stack usage is a practical advantage of a stack-oriented paradigma and a reason to adopt such paradigma, as asked.
So, I think it is worth listing the advantages of stack usage instead of heap allocation for completeness:
CPU Time -- The time cost of memory allocation in the stack is practically free: doesn't matter if you are allocating one or one thousand integers, all it takes is a stack pointer decrement operation. example
Memory leak -- There are no memory leaks when using the stack only. That happens naturally without additional code overhead to deal with it. The memory used by a function is completely released when returning from each function even on exception handling or using longjmp (no referencing counting, garbage collection, etc).
Fragmentation -- Stacks also avoid memory fragmentation naturally. You can achieve zero fragmentation without any additional code to deal with this like an object pool or slab memory allocation.
Locality -- Data in stack favors the data locality, taking advantage of cache and avoiding page swaps.
Of course, it may be more complicated to implement, depending on your problem, but we shall favor stack over heap always we can in any language. Leave malloc/new to be used only when actually needed (size or lifetime requirements).
For some people it's easier to think in terms of managing stacks than other paradigms. At the very least, doing some hacking in a stack-based language will improve your ability to manage stacks in general.
Aside: in the early days of handheld calculators, they used something called Reverse Polish notation, which is a very simple stack-based postfix notation, and is extremely memory efficient. People who learn to use it efficiently tend to prefer it over algebraic calculation.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I would like to hear from you folks that have achieved a high-level of proficiency in F# (and also in functional programming in general too) what should be my steps from now on to become a better/professional F# programmer?
I already know much of the F# syntax and have some years of experience with C++. My goal is, as an engineer and mathematician, to design better scientific libraries (linear algebra packages, partial differential solvers, etc.).
what should be my steps from now on to
become a better/professional F#
programmer?
Keep coding everyday :)
I jumped on the F# train in Sept '07, before that I had a boatload of C# experience. It took about 3 months or so for me to stop writing code as C# with a little funnier syntax and start picking up on the right coding style :)
Tips and things that helped me:
I found that F# makes it really hard to write non-idiomatic code, really easy to write good, clean code. If you find yourself fighting the compiler, 9 times out of 10 your doing something wrong. Go back to the drawing board and try again.
The entire concept of immutability was a mystery at first, but implementing all of the data structures from Okasaki's Purely Functional Data Structures was hugely helpful.
During some slow days at work, between '08 and '09, I wrote a wikibook. I haven't looked at it in a while, but I'm sure its really bad --- but, the experience of explaining the language to others was a good jumpstart for someone like me who normally wouldn't have enough motivation to start a pet project in F# :)
Map, Fold, and Filter are your friends. Try to express algorithms in these functions rather than implementing a loop with recursion.
Non-tail recursive functions are almost always easier to read and write. See here.
Project Euler. Lots of people recommend it, I didn't find it particularly helpful at all. You might get more use from it than me if your a mathematician, however.
<3 unions! Use them!
Falling back on mutable state -- big no-no. At least for beginners. The worst beginner code is full of mutables and ref variables. Immutability is an alien concept at first, so I recommend writing fully stateless programs for a while.
Still, the best advice is just keep coding everyday.
Hope that helps!
-- Juliet
Like any other language now that you know the syntax and the basics it's time to write code and more code.
Make sure you have the core concepts of functional programming down.
Work on a large project so you also get familiar with the large and not just the small.
Write a few immutable data structures.
Work on a large project without using inheritance.
If your familiar with design patterns implement some of them in a purely functional way and notice how some of them disappear.
F# is about mixing functional and OOP styles. Once you've done a fare amount of abstraction without inheritance bring it back and start mixing the styles together. Find a balance.
Since your goal as an engineer and mathematician is to design better scientific libraries may I suggest as a learning exercise working on a video game style simulation. Something that involves physics and math but also requires control of state.
I can only agree that trying to explain functional programming to others is a great way to learn it. I spent a lot of time about thinking the structure of my F# book and I think it really helped me to understand how functional concepts relate. Even giving a talk on F# in your company or to your friends should have a similar effect.
When I started learning F#, I started working on the F# WebTools project. I think this was quite useful, because many components of the project were perfect for functional programming, so I learned many functional tricks (because they were the best way to solve the problem). The project processed source code tree of F# and translated it to JavaScript, so I was using a lots of recursive functions and discriminated unions.
The area you're working in is quite different than my, so I cannot give you any specific advice, but it is a good idea to write programs in a clear functional way - even if you think that it would look nicer if you wrote it in the C++ style. When you write it, you'll probably find some way to simplify your code.
So, I think that the tips I could give are:
Try to explain F# to others - this helps you to organize ideas in your mind
Pick good problems to start with - e.g. algorithmic problems, processing tree structures, etc.
Write as much F# as you can and don't be afraid to start with a solution that does not look perfect to you - I rewrote my first program so many times!
you very probably don't want to hear from me as I have not achieved a high level of proficiency with F#, but I have set myself the goal of getting there (much like your self).
I thought I might suggest what has turned out to be my biggest learning tool: Stubbornness.
I set my self a large-ish project (a game, just as gradbot suggests). I then decided to code using as much immutable data as possible regardless of the performance costs.
Then if I couldn't find a way to use immutable data I'd come here and ask for help.
The hoops this stubborn approach forced me to jump through has been a brilliant learning exercise, as (just as Juliet mentions) F# allows you to write really ugly C# if you let your self get lax.
Right now I have tile based 2D world and a little man who can find his way to the treasure and back home again using A* path-finding ... The only thing I mutate is the title of the window it's displayed in.
I only got serious about learning F# towards the end of July (I'd dabbled before then) and this project has taught me a huge amount, along with the help of the guys here at StackOverflow.
The other answers do a good job of suggesting ways to practice your F# writing skills, which is obviously very important. However, something which doesn't seem to have been emphasized much is reading F# code, which is just as important in my opinion. There are a lot of people doing cool stuff with F#, and one of the best ways to learn about the different corners of the language is to read about what they're doing. This will help you pick up idiomatic style and will also expose you to more design patterns, language features, and functional programming techniques than you would be likely to encounter if you were just solving a problem using F# on your own.
The F# blogs syndicated on Planet F# are a good place to start, but there are also several excellent books and presentations on the language.
This only answers part of your question, but as you talk about wanting to create libraries in F#, the F# component design guidelines just came out:
http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/fsharp-component-design-guidelines.pdf
If you are interested in scientific libraries I suggest you to take a look at Jon Harrop's F# for Scientists.
Also to catter for your mathematician side I suggest you to read Doets-Van Eijck The Haskell Road to Logic, Maths and Programming, although written in Haskell, you will certainly be able to follow most of the text, and re-implementing the samples in F# could be a nice exercise.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
From day 1 of my programming career, I started with object-oriented programming. However, I'm interested in learning other paradigms (something which I've said here on SO a number of times is a good thing, but I haven't had the time to do). I think I'm not only ready, but have the time, so I'll be starting functional programming with F#.
However, I'm not sure how to structure much less design applications. I'm used to the one-class-per-file and class-noun/function-verb ideas in OO programming. How do you design and structure functional applications?
Read the SICP.
Also, there is a PDF Version available.
You might want to check out a recent blog entry of mine: How does functional programming affect the structure of your code?
At a high level, an OO design methodology is still quite useful for structuring an F# program, but you'll find this breaking down (more exceptions to the rule) as you get down to lower levels. At a physical level, "one class per file" will not work in all cases, as mutually recursive types need to be defined in the same file (type Class1 = ... and Class2 = ...), and a bit of your code may reside in "free" functions not bound to a particular class (this is what F# "module"s are good for). The file-ordering constraints in F# will also force you to think critically about the dependencies among types in your program; this is a double-edged sword, as it may take more work/thought to untangle high-level dependencies, but will yield programs that are organized in a way that always makes them approachable (as the most primitive entities always come first and you can always read a program from 'top to bottom' and have new things introduced one-by-one, rather than just start looking a directory full of files of code and not know 'where to start').
How to Design Programs is all about this (at tiresome length, using Scheme instead of F#, but the principles carry over). Briefly, your code mirrors your datatypes; this idea goes back to old-fashioned "structured programming", only functional programming is more explicit about it, and with fancier datatypes.
Given that modern functional languages (i.e. not lisps) by default use early-bound polymorphic functions (efficiently), and that object-orientation is just a particular way of arranging to have polymorphic functions, it's not really very different, if you know how to design properly encapsulated classes.
Lisps use late-binding to achieve a similar effect. To be honest, there's not much difference, except that you don't explictly declare the structure of types.
If you've programmed extensively with C++ template functions, then you probably have an idea already.
In any case, the answer is small "classes" and instead of modifying internal state, you have to return a new version with different state.
F# provides the conventional OO approachs for large-scale structured programming (e.g. interfaces) and does not attempt to provide the experimental approaches pioneered in languages like OCaml (e.g. functors).
Consequently, the large-scale structuring of F# programs is essentially the same as that of C# programs.
Functional programming is a different paradigm for sure. Perhaps the easiest way to wrap your head around it is to insist that the design be laid out using a flow chart. Each function is distinct, no inheritance, no polymorphism, distinct. The data is passed around from function to function to make deletions, updates, insertion, and create new data.
On structuring functional programs:
While OO languages structure the code with classes, functional languages structure it with modules. Objects contain state and methods, modules contain data types and functions. In both cases the structural units group data types together with related behavior. Both paradigms have tools for building and enforcing abstraction barriers.
I would highly recommend picking a functional programming language you are comfortable with (F#, OCaml, Haskell, or Scheme) and taking a long look at how its standard library is structured.
Compare, for example, the OCaml Stack module with System.Collections.Generic.Stack from .NET or a similar collection in Java.
It is all about pure functions and how to compose them to build larger abstractions. This is actually a hard problem for which a robust mathematical background is needed. Luckily, there are several patterns with deep formal and practical research available. On Functional and Reactive Domain Modeling Debasish Ghosh explores this topic further and puts together several practical scenarios applying pure functional patterns:
Functional and Reactive Domain Modeling teaches you how to think of
the domain model in terms of pure functions and how to compose them to
build larger abstractions. You will start with the basics of
functional programming and gradually progress to the advanced concepts
and patterns that you need to know to implement complex domain models.
The book demonstrates how advanced FP patterns like algebraic data
types, typeclass based design, and isolation of side-effects can make
your model compose for readability and verifiability.