-1

I watched a talk in live where the person said they at work are doing Scala functionally, they use case classes, transform a type to another, immutability everywhere, etc.

How does this actually work? I'd love to see a simple hello world application with pure functional approach.

Also I can't see how can I get rid of var altogether because sometimes I just need it.

Tower
  • 98,741
  • 129
  • 357
  • 507
  • 1
    You just do it. Do you have a specific example in mind that you fail to translate into purely functional style? Hello world would look the same way, if we ignore that fact that it's impure and thus would be eschewed (but obviously necessary). –  Oct 26 '12 at 18:59
  • maybe this would help you: http://stackoverflow.com/questions/727078/whats-so-great-about-scala http://stackoverflow.com/questions/4540831/scala-make-my-loop-more-functional – Kummo Oct 26 '12 at 19:07

2 Answers2

5

There is a course on Coursera just about that.

ghik
  • 10,706
  • 1
  • 37
  • 50
1

"Hello world" is not really good to demonstrate the functional approach, as there is nothing functional about it. (In fact, as @delnan noted, writing to the standard output is considered a side effect, so this program can never be made purely functional.)

The most likely reason for you to need var is using imperative style loops, which is indeed not the functional approach. The functional equivalent would be to either use some of the available filter / transform functions on a collection, or use recursion.

Simple example: finding all strings in a list which start with 'F'. Imperative style (Java):

List<String> result = new ArrayList<String>();

for (String s : strings) {
  if (s.startsWith("F")
    result.add(s);
}

Imperativeness would be even more pronounced with the old style iterator loop.

In contrast, functional style could be something like:

val result = strings.filter(_.startsWith("F"))
Péter Török
  • 114,404
  • 31
  • 268
  • 329
  • I think it would be more correct to illustrate functional approach via recursion. Because it's not clear what happens when you call "filter". You can have a for loop inside the filter, will it stay functional then? – Soteric Nov 25 '13 at 12:29