Functional programming.

Status
Not open for further replies.
Hi all,

I've been reading about functional programming lately and it is certainly interesting material. I don't pretend to understand everything and i hope this isn't a stupid observation:

The one thing i find weird is the immutability aspect of objects.

I can understand why it is done, but wouldn't this cause a big hit in performance?

For every update to an object you return a new one. Meaning you need to instantiate a whole new object.

Am i making sense, or is this a really dumb observation and i understand even less than i thought i did. :)

I am reading C# examples so maybe this is an artifact of shoehorning functional aspects in an O O language/runtime?
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Depends, it provides some issues witrh naive implementations but different oppurtunities for efficiencies.

There is for example no *rule* in many lanagues about where an object has to be allocated, only it's lifetime and it's semantics on being referenced by a new variable.

Once you are immutable there is no need for value/reference semantics to differ (unless you care about identity and again languages with strong push to immutability frequently avoid pushing you into using that technique) at which point it is only lifetime that matters.

Thus if the language's function calls are being (largely) implemented via a stack being able to allocate on the stack as needed means you don't get huge performance hits due to GC pressure (most Functional languages are implemented with GC of some form since deterministic lifetime is exceptionally hard to work out if you have closures with value capture and the like).

There are many problem domains for which mutability is important, I would say especially in certain areas where you are attempting to model real world business interactions. If Mrs Blah phones up and wants to change her surname to Mrs Bloggs then modelling this as the replacement of her with a new entity with a different name you're going to start finding some leaky abstractions.

However even given that (and I definitely work in a field where mutable state is very important for performance) IME I would rather that c#'s default for instance fields was readonly and I would rather that you could annotate local variables as readonly (thus making them values).

Choosing to allow mutation should be IMO a deliberate decision in many languages, even largely imperative ones.

Also you would be *amazed* what the modern compilers in functional languages can do, especially with the rough equivalent of whole program optimization.

tl;dr the semantics exposed to you the human, through the language is NOT the way the implementation on the computer has to actually do it if it can achieve your semantics in some other way. The only times you will find this a pain is when you come to debug and the two things are sufficiently divergent that the model you expect cannot be expressed anymore.
 
Also you would be *amazed* what the modern compilers in functional languages can do, especially with the rough equivalent of whole program optimization.

Yeah, there are some pretty impressive compilers out there for languages where a lot of money has been thrown at the performance issue over the years. I was testing out some minimum-spanning-tree finding algorithms in a few different languages early last year for a research project, and even the free SBCL Lisp compiler (never tried one of the commercial ones) on x86 Linux was pretty impressive. (Though that's far from a purely functional language.) I was able to get it to something like 95% of my pure C implementation's speed, and it was at least 10 times faster than I could get Python (I want to say more than 100x, but it's been over a year since I was playing around with it, and I don't remember for sure).
 
koala":23s5oycv said:
Actually, I'd say that I rarely want variable mutation in the code I write- most mutation happens in an SQL database. So if I switched full time to a functional language, I might not miss much variables...

This is my experience as well. Sure, standard algorithms and complex computations often rely on mutation for speed, but who really writes that code any more, as opposed to code that just shuffles data around somewhere and sends it off again?
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
aliftedlorax":1m8faot5 said:
koala":1m8faot5 said:
Actually, I'd say that I rarely want variable mutation in the code I write- most mutation happens in an SQL database. So if I switched full time to a functional language, I might not miss much variables...

This is my experience as well. Sure, standard algorithms and complex computations often rely on mutation for speed, but who really writes that code any more, as opposed to code that just shuffles data around somewhere and sends it off again?
Even in SQL, I tend to prefer append-only table designs.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
Also you would be *amazed* what the modern compilers in functional languages can do, especially with the rough equivalent of whole program optimization. tl;dr the semantics exposed to you the human, through the language is NOT the way the implementation on the computer has to actually do it if it can achieve your semantics in some other way.
This. The fact that you, the programmer, are forced to treat the objects as immutable lets the compiler do all sorts of things to optimize that it simply wouldn't be able to do without that guarantee. Think automatically threading code, for instance. No share state means no shared state to synchronize.

That's my totally-non-expert understanding of it, anyways.
 
Ok clear, so i have been reading up on F# and it looks pretty cool actually.

It introduces mutable properties as a way to mutate variables, but isn't this defeating the purpose/main strengths of a functional language? Don't you end up with the worst of both worlds? ( I know about the syntax being spoken of as more declarative as being a plus, the unmutable nature of varables is a second plus. )

And another thing, how would this tie into something like the entity framework? In my understanding the ORM creates classes and entities from a db or what have you, and gives you a way to store your objects in a DB. So you create objects from a DB and can work with them, if you can't mutate these objects through F# and need to create a new object whenever you would like to update it, how would this work?

Am i making this harder than it really is?

Thanks for the help so far. :)
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
f# is not a strict language (strict means no mutation of state). I'm quite glad of that because there really is quite a lot of the world which A) is mutable and B) cannot be efficiently handled by monads.
That said it encourages immutability (it is always the default) which is IMO sensible.

Be careful on terminology here by the way, it matters quite a bit.

f# has *mutable references* essentially a way of creating a variable. Everything else that you would normally call a variable is in fact a *value* since it cannot vary once defined.

Because f# is non strict it is quite capable of mutating things which are mutable (like for example the classes created by the entity framework). Since this sort of thing is meant to be less common f# has syntax for it different than c# (and many other imperative languages) which is "<-" instead of (say) "=" which in f# is actually equality.

f# incidentally is nothing special in this regard, it simply borrows most of this from ML, its functional basis. It has moved away from it heavily in syntax since the 2.0 release, and considerably in it's object model which is inherently based on being efficiently implemented with the .Net CLR type system.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I have been reading quite a lot on it and it's something i would really like experiment with.

Learning any decent functional language is IMO a key learning experience for any programmer.

You don't have to use it for long afterwards, nor even remember the syntax, just understand the way it causes you to structure things and the pros and cons involved.

Personally I think they encourage terseness to the point of being hard to maintain, which is something that (again IMO) should be fought against, but you can understand this better after trying it.

Come back to some imperative only code months later and you may find the "what" obscured by the "how". Conversely in FP you may wind the "why" unclear (personally I often have problems reading the "what", the significant punctuation use, and far more varied type system in f# ends up leaking out of my head if I don't use it for even a week or so)
 
There was a post, a few years ago, I think by aliftedlorax? that in jest walked through the thought process of eliminating unnecessary stuff from an imperative program and ending up "accidentally" with LISP.

It was a joke, but something clicked about functional programming when I read that.

I'm going to try to find it.

EDIT:
Great success!
Here it is
viewtopic.php?f=20&t=189991&p=4892685#p4892685
 

Bad Decaf

Seniorius Lurkius
42
Subscriptor
f# is not a strict language (strict means no mutation of state).

In the context of functional programming, strict usually refers to call-by-value semantics for the evaluation strategy. "lazy" call by name semantics, such as implemented in Haskell, are an alternative to strict evaluation.

As a guess, given it's ocaml heritage, I would think the default in F# is probably strict evaluation.

See http://en.wikipedia.org/wiki/Functional_programming#Strict_versus_non-strict_evaluation for a brief overview.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I found the Experts f# very good but it's not really an intro to FP, it assumes a passing familiarity with quite a bit. Nonetheless it's excellent. http://books.google.com/books/about/Exp ... rMkjVxahMC (get the 2.0 edition)

Introductory books wise I have heard good things about "Real World Functional Programming: With Examples in F# and C#", if you have a solid c# background that will likely ease you into the concepts well.

Quite a lot changed in the 2.0 release so many older books and tutorials went out of date, have a care.

I have used the following online resources quite a bit:

I think this is an excellent way to cover quite a few of the core concepts very quickly.
http://www.ctocorner.com/fsharp/book/default.aspx
This online wikibook is not bad:
http://en.wikibooks.org/wiki/Programming:F_Sharp

finally the msdn documentation is finally there and is a reasonable guide to the sytax for various constructs if you're happy with a BNF like structure.

Avoid anything using the old style verbose syntax. It's totally deprecated and you'll see next to nothing using it.

I found that doing Project Euler in f# was a pretty good way to get going, especially if you will end up doing any numeric programming, since there are some aspects that grate (no implicit conversion from int to float being a biggy) that cause annoyance but also the very powerful abilities of inline more than make up for this.
 
"Real World Functional Programming: With Examples in F# and C#"

I am reading this one. It's pretty good but i find it hard to wrap my head around a some of the concepts.

There is also a Fsharp wiki which has a couple of nice tutorials. Although sometimes it is hard to follow what they are exactly doing.

Must be me though :)

Shuggy already linked the wiki.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I am reading this one. It's pretty good but i find it hard to wrap my head around a some of the concepts.

Some of FP is a really different way of thinking about things.
I was taught FP first, so I can't really give you any pointers on learning it the other way.

get your head around fold, it's very commonly used instead of loops.
Look at some of your existing code base, See if you have any classes/interfaces with only one real method of any significance on them. Think about how they could be replaced by a function (with state capture by a closure if need be) and how you might make your code base simpler/more flexible if you didn't require the explicit class/interface but simply the function. Think how you could do various things simply by composing the function with others.

Think about functions, which take another function (and perhaps more things) and provide a new function, which subtlyy alters the behaviour of the other one.

However do remember that sometimes there *is* value to naming things, despite it leading to an extra few lines of definition.

If you see "Function from a tuple of (Function from int to String, Function from String to 'x) to Function from (int to 'x)" all over the place used for the same purpose naming it for that purpose adds value. Just because the compiler is smart enough to know this doesn't mean humans like reading it that way (this is a very tame example, I see type inferred signature popups in VS which span two lines on a 2560pixel monitor. They make me sad.
 
Bastard, following up on what Shuggy said, I think the main concepts are simple and natural. When learning FP, keep in mind that functions are ubiquitously useful and natural abstractions.

Very often I'll find myself doing something like this in Java:
Code:
List<Person> people; // initialized somehow
List<String> phoneNumbers = new ArrayList<String>();
for (Person person : people)
  phoneNumbers.add(person.getPhoneNumber());

And then I'll find myself doing this elsewhere:
Code:
List<Person> people; // initialized somehow
List<String> emails = new ArrayList<String>();
for (Person person : people)
  emails.add(person.getEmail());

You see the pattern: we take a list of things and create a new list where each element is the result of applying some "transformation" (such as calling getEmail()) to an element of the original list. Unfortunately, Java gives me no elegant way to abstract this pattern out and make a generic method to do this (you could do it but with a lot of unnecessary braces).

What would be more natural is to write something like this once:
Code:
<A, B> List<B> map(Function<A, B> transformation, List<A> items) {
  List<B> mappedItems = new ArrayList<B>();
    for (A item : items)
      mappedItems.add(transformation.evaluate(item));
  return mappedItems;
}

Then I could use it in many situations like:
Code:
map(Person.getEmail(), people)
The map "function" condenses 3 lines of code into a simple expression.

----------------

Another situation I often find myself in is computing an aggregate value from a collection:
Code:
Collection<Integer> numbers;
int sum = 0;
for (int number : numbers)
  sum += number;

Code:
Collection<Integer> numbers;
int product = 1;
for (int number : numbers)
  sum *= number;

Now we want to abstract out two things: the initial value (0 for sum, 1 for product) and the operation for combining each new value (+ for sum, * for product). So we want a general procedure to "fold" values one at a time into an aggregate value, like:
Code:
<A, B> <B> fold(B aggregate, Function2<A, B, B> operation, List<A> items) {
  for (A item : items)
    aggregate = operation.evaluate(item, aggregate);
  return aggregate;

Now, it might be nice to define sum and product operations in terms of fold:
Code:
let sum(numbers) = fold(0, +, numbers)
let product(numbers) = fold(1, *, numbers)

----------------

Both of these examples, map and fold, are "higher order functions": functions taking functions. But they aren't at all complex or scary. They're simple and useful. They can even be combined easily: to get the total popularity of a collection of people, just say something like:
Code:
sum(map(Person.popularity(), people))
The equivalent Java code would be 5 times as long.

At its core, functional programming really is that simple. There are more advanced features in many functional languages, such as macros, monads, etc. More importantly, the extreme power of functions as an abstraction tool can lead to code that's surprisingly complex given its size. However, more often than not, the code is just a composition of simple features, and by mentally breaking it down, it can be understood. (On the other hand, spaghetti procedural code can be extremely hard to break down as each component often relies on side effects of other components.)
 
I don't know if it's hectoring to point out that "immutable objects" are not necessary to a functional programming language. Objects in most languages are a pairing of state with behavior. Functional languages isolate stateful behavior from a-temporal/non-stateful behavior. One way of doing this is immutable objects, which is more familiar to someone who's done OO in other languages. Another way is to not have a concept of objects at all - see Haskell.

I'd like to make a distinction between the performance of an implementation and the performance of the semantics of a language. By "semantic performance", I mean the optimizations that a compiler is allowed to make in theory. I think it's a far more interesting question. And now I get to say that the semantics of immutable objects do not entail a performance hit over the semantics of mutable objects. Doing operations on the language construct of 'immutable objects' is just another way of expressing a computation statelessly and is equivalent to other lambda expressions. Meanwhile, the performance of lambda expressions are equivalent, in theory, to imperative code. (Think of "immutable objects" as a way of expressing a function within a particular type class with baked in bindings. Conceive of each successive method call as stacking on another "let" expression in Haskell).

However, as usual, when smart programmers get to fiddle with bits and memory directly (as in when they are manipulating real, stateful objects), then they're likely to be able to eke out more performance for many kinds of algorithms, using clever, domain-specific, tactical optimizations. I think the only time that this distinction is practically relevant today is in the mobile space, where disparate architectures don't have optimizing compilers available. (Though, e.g., Haskell can compile to optimized C code).
 

Raqem

Ars Tribunus Angusticlavius
7,586
newwb":1q8dnjd4 said:
Bastard, following up on what Shuggy said, I think the main concepts are simple and natural. When learning FP, keep in mind that functions are ubiquitously useful and natural abstractions.

Very often I'll find myself doing something like this in Java:
Code:
List<Person> people; // initialized somehow
List<String> phoneNumbers = new ArrayList<String>();
for (Person person : people)
  phoneNumbers.add(person.getPhoneNumber());

And then I'll find myself doing this elsewhere:
Code:
List<Person> people; // initialized somehow
List<String> emails = new ArrayList<String>();
for (Person person : people)
  emails.add(person.getEmail());

You see the pattern: we take a list of things and create a new list where each element is the result of applying some "transformation" (such as calling getEmail()) to an element of the original list. Unfortunately, Java gives me no elegant way to abstract this pattern out and make a generic method to do this (you could do it but with a lot of unnecessary braces).

What would be more natural is to write something like this once:
Code:
<A, B> List<B> map(Function<A, B> transformation, List<A> items) {
  List<B> mappedItems = new ArrayList<B>();
    for (A item : items)
      mappedItems.add(transformation.evaluate(item));
  return mappedItems;
}

Then I could use it in many situations like:
Code:
map(Person.getEmail(), people)
The map "function" condenses 3 lines of code into a simple expression.

It would be closer to this:
Code:
<A, B> List<B> map(String methodName, List<A> items) {
    Method method = items.get(0).getClass().getMethod(methodName);
    List<B> mappedItems = new ArrayList<B>();
    for (A item : items)
        mappedItems.add(method.invoke(item));
    return mappedItems;
}

To invoke:
Code:
map("getEmail", people);

Of course, this would require some null checking (left out for brevity) and introduces a run-time error possibility (instead of doing the implied compile-time checking in your example). I'm not sure how one would do the fold feature without creating new classes to represent the operations.
 
Raqem":3d8lp2tg said:
It would be closer to this:
Code:
<A, B> List<B> map(String methodName, List<A> items) {
    Method method = items.get(0).getClass().getMethod(methodName);
    List<B> mappedItems = new ArrayList<B>();
    for (A item : items)
        mappedItems.add(method.invoke(item));
    return mappedItems;
}

To invoke:
Code:
map("getEmail", people);

Of course, this would require some null checking (left out for brevity) and introduces a run-time error possibility (instead of doing the implied compile-time checking in your example). I'm not sure how one would do the fold feature without creating new classes to represent the operations.
I was writing Java-inspired pseudocode, not real Java code. I understand you could do it your way, as long as you're willing to add a bunch of checked exceptions to your method, including the evil InvocationTargetException, but as you note you lose compile-time safety. Reflection is a very poor way to mimic functional programming in Java.
 

Horatio

Ars Legatus Legionis
24,430
Moderator
Of course, this would require some null checking (left out for brevity) and introduces a run-time error possibility (instead of doing the implied compile-time checking in your example). I'm not sure how one would do the fold feature without creating new classes to represent the operations.
Does Java not support lambdas? That would simplify it considerably. So in C# it would be
Code:
var emails = people.Select(p => p.Email);
Folds are also built-in.
 
Nothing about the Function<D, R> I wrote implies whether it's used lazily or not. You could write a collection wrapper that applies it as the collection is viewed, or creates a new collection upfront. Of course it's far easier to have a map function built in than to have to write it and I agree with the lazy choice - it's trivial to make the lazy collection eager by copying its contents to a new collection but harder to make an eager collection lazy.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Richard may have been referring to the IQueryable interface with the associated composition of operations like Where, Select et al which keep things in IQueryable (as opposed to IEnumerable) and thus allow deferred execution (or other shenanigans via the expression trees as with LINQ to SQL et all)

Alternatively he was not referring to your example as such, just the pain involved in Java if you were to want to construct lazy (or indeed infinite) sequences since the boilerplate:actual useful code ratio for things like iterator blocks (generators in python, there's plenty of languages with the feature) is very high. Worse writing the state machine yourself is both verbose and obscures the behaviour (as opposed to the function example you gave where the boiler plate is merely a buffer)

Or something else even cooler the likes of us aren't allowed to play with yet :)
 
ShuggyCoUk":2wkdrr47 said:
Richard may have been referring to the IQueryable interface with the associated composition of operations like Where, Select et al which keep things in IQueryable (as opposed to IEnumerable) and thus allow deferred execution (or other shenanigans via the expression trees as with LINQ to SQL et all)

Alternatively he was not referring to your example as such, just the pain involved in Java if you were to want to construct lazy (or indeed infinite) sequences since the boilerplate:actual useful code ratio for things like iterator blocks (generators in python, there's plenty of languages with the feature) is very high. Worse writing the state machine yourself is both verbose and obscures the behaviour (as opposed to the function example you gave where the boiler plate is merely a buffer)

Or something else even cooler the likes of us aren't allowed to play with yet :)
Java's perfectly fine for lazy programming. All you need is this and you're all set:
Code:
static interface Thunk<E> {
  E get();
}

static Function<Thunk<D>, Thunk<R>> lazify(final Function<D, R> f) {
  return new Function<Thunk<D>, Thunk<R>>() {
    public Thunk<R> invoke(final Thunk<D> arg) {
      return new Thunk<R>() {
        public R get() {
          return f.invoke(arg.get());
        }
      }
    }
  }
}

Now to get the hash code of "123", you can say:

Code:
Thunk<Integer> lazyHashCode = lazify(
  new Function<String, Integer>() {
    public Integer invoke(String s) {
      return s.hashCode();
    }
  }
).invoke(
  new Thunk<String>() {
    public String get() {
      return "123";
    }
  }
);

Easy as 1-2-3. :)
 
Yes, it's also not so useful an implementation because the function implementation should take a thunk so that it can evaluate without computing some arguments.

Back to the OP, this discussion about laziness is one feature of some functional languages. Basically, an expression isn't evaluated when it's encountered at runtime. Instead, it's passed around as an "unevaluated value" called a thunk and it's only evaluated if it's actually used (printed to the console or determines which condition of a conditional is active or something like that). It's like the ternary conditional in many languages:
Code:
condition ? ifTrue : ifFalse
There's special logic in most languages that only evaluates whichever expression, ifTrue or ifFalse, matches the value of the condition. But instead, if that were written as a function call with 3 arguments:
Code:
if(condition, ifTrue, ifFalse)
("if" keyword notwithstanding), both expressions would be evaluated before "if" is called if the language isn't lazy. If the language were lazy however, neither expression would be evaluated upfront and you could write a procedure that actually works like the ternary operator as:
Code:
<E> E if(boolean condition, E ifTrue, E ifFalse) {
  if (condition)
    return ifTrue;
  else
    return ifFalse
}
The result is that the condition must be evaluated to know which expression to return but neither expression's value is actually used, so neither expression is evaluated.
 
Status
Not open for further replies.