Ikke's blog » functional programming http://eikke.com 'cause this is what I do Sun, 13 Feb 2011 14:58:55 +0000 en-US hourly 1 http://wordpress.org/?v=3.4.1 On Functional Programming Languages http://eikke.com/on-functional-programming-languages/ http://eikke.com/on-functional-programming-languages/#comments Wed, 07 Apr 2010 21:50:38 +0000 Nicolas http://eikke.com/?p=173 As a programming-language adept I’ve been studying the ideas, concepts and theory of functional programming (FP) and FP-related languages for about 2 years now, still learning new things everyday.

Recently a ‘FP User Group’ was started by some people at Ghent University, called GhentFPG, and the first meeting took place last thursday, with great interest from students, university employees as well as people working in the industry. You can find some more info in the GhentFPG Google Group or in the wiki (where you can also find the slides of the presentations given during the first meeting).

Some days ago someone new to FP posted a message on the mailing list, asking which language he should study, among other things.

Since I think my reply might be of general interest (also outside GhentFPG), I decided to post a copy on this blog as well (note I did add some extra markup). Comments welcome!

Based on my experience (which is biased, obviously):

  • Functional Programming is not only a language-related thing. FP
    languages do enforce you to apply functional paradigms, but you can
    easily follow these paradigms in lots of other (more mainstream?)
    languages as well: it is easier to learn people a paradigm using a
    language they already know, rather than telling them FP is really cool
    and useful and interesting, but requires them to learn a new
    language/toolchain/… first.

    Not talking about Java or C++ or something similar here, rather Python
    and Ruby.

  • If you’re into Java/C#/…, Scala is a really good introduction to FP:
    it allows you to write OOP code just like you do already, but also
    provides you lots of FP-related features, and pushes you gently into the
    FP approach. The book “Programming in Scala” by Odersky et al. (the main
    author of Scala) is IMO a really good intro to both Scala as well as the
    FP concepts it provides, not only showing them but also explaining
    gently why they’re useful, and why they’re ‘better’ than the approaches
    you’re taking already.

    The Scala type system is rather interesting as well.

    It’s the gentle path, so you want ;-) Learning Scala before reading
    Real World Haskell‘ certainly helped me a lot to understand the latter.

  • Haskell is an incredibly interesting language because of the concepts
    it adopted and types it provides, but it does require an immediate mind
    switch when coming from a non-OOP world (I once spent about 2 hours to
    explain a Java-guy how classes and instances in Haskell relate to
    classes and instances in Java, it wasn’t obvious). “Real World Haskell”
    is certainly worth a read (and if you read “Programming in Scala” as
    well, you’ll notice lots of similarities).

    I for one can read Haskell code pretty easily and learned lots of
    CS/math things thanks to learning it, but I’m (still) unable to write
    non-trivial code (I need some good project to get my hands dirty I
    guess).

  • Erlang is really interesting from a (very specific) feature
    perspective: high-availability, distributed computing, the actor system
    and the OTP library on top of it,…

    It’s a rather ‘old’ language, but I kind of like it. Some people do
    complain about the syntax, but once you figured out ‘,’, ‘;’ and ‘.’ are
    used almost the same as they are in ‘human’ written language, everything
    becomes obvious :-)

    Do note though Erlang is not a normal general-purpose language. You can
    code +- everything you want using it, but it’s really targeted to
    distributed/high-available/network applications. You most likely won’t
    use it to solve mathematical problems or write a game. It’s really good
    at what it’s built for though.

    One final note: please don’t ever make the mistake I made. If you know
    Erlang, and take a look at Scala (which also has an actor library in the
    standard distribution, as well as the more advanced Akka-library), don’t
    judge Scala as being a competitor for Erlang, they’re both completely
    different languages targeting different applications. ‘Scala’ is not
    about ‘scalability’ as Erlang is (it’s a “Scalable Language”).

  • F# (and most likely OCaml as well, although I never used it though) is
    certainly worth a look as well. I only read 3/4th of a book on it, but
    it looks really promising and interesting.

  • There’s obviously all sorts of Lisp dialects. I have no opinion on
    them, never looked into any Lisp closely enough. I only wrote some
    Clojure (a Lisp-dialect for the JVM) code one day, but need to learn
    more about the Lisp-way of programming. Clojure seems to be interesting
    because of the deep integration of Software Transactional Memory (STM)
    in the language (yet another approach to concurrency ;-) ).

As for the IDE question: Vim and a decent terminal are all you need,
luckily none of the above languages require you to learn how to use a
toolchain which enforces you (or some magic IDE) to write 500 lines of
XML-based build ‘programs’ or other insanities.

My advice: pick some language, learn it, but make sure you don’t only
learn the language, but especially the concepts (type system,
higher-order stuff, list manipulation,…). Then pick some other
language and learn it as well (which will be easier since you got the
concepts already) and so on.

And read tons of papers available on the internet in between ;-) Even if
you don’t understand a paper completely, you’ll pick up some things
already, and re-reading it 2 weeks later helps a lot :-D

Just my .02,

Nicolas

]]>
http://eikke.com/on-functional-programming-languages/feed/ 3
Scala tail recursion and decompiler adventures http://eikke.com/scala-tail-recursion-decompiler/ http://eikke.com/scala-tail-recursion-decompiler/#comments Wed, 12 Aug 2009 22:31:03 +0000 Nicolas http://eikke.com/?p=129 I’ve been into Scala lately. More about it will follow later, but there’s something I found out which I really like.

Last couple of days I wrote some very basic Scala snippets, containing constructs which would be non-trivial or ‘unusual’ to write in Java, compile it to a class file, and then use a Java decompiler to figure out how the Scala compiler maps those constructs to JVM bytecodes.

There’s one thing which took my attention: looks like (basic) tail-recursive functions are optimized into while-loops! This only happens if the last call of a function is a call to itself (the most basic form of tail recursion), but it’s an interesting feature anyway… No more need to put socket accept handling in an infinite while loop :-)

A little demo. First, here’s a Scala object which implements a very basic ‘reduce’ function:

object Reducer {
  def reduce[T, V](fun: (V, T) => V, values: List[T], initial: V): V = {
    if(values isEmpty)
      return initial
    val next = fun(initial, values head)
    return reduce(fun, values tail, next)
  }

  def main(args: Array[String]): Unit = {
    val values = List(1, 2, 3, 4)
    val sum = reduce[Int, Int]((x, y) => x + y, values, 0)
    println("Result: " + sum)
  }
}

We can compile and run this, and it’ll output the expected result ’10′:

MacBook:reduce nicolas $ scalac Reducer.scala 
MacBook:reduce nicolas $ scala Reducer
Result: 10

Now we can open the generated class files in JD. There are a couple of them (it’s interesting to take a look at all of them and figure out what they represent exactly), but in this case we need ‘Reducer$.class’, which contains the implementations of our public functions, including ‘reduce’.

Here’s the Java version of the ‘reduce’ function:

public <T, V> V reduce(Function2<V, T, V> fun, List<T> values, V initial)
{
  while (true)
  {
    if (values.isEmpty())
      return initial;
    Object next = fun.apply(initial, values.head());
    initial = next;
    values = values.tail();
  }
}

‘Function2′ is a built-in Scala type which represents a function taking 2 parameters. As you can see, this code does exactly the same as our Scala version and is most likely the way we’d write the code manually as well (the only thing I don’t get is why ‘next’ is an Object and not a ‘V’, I might figure that out later), but without forcing us to write the imperative code, whilst still producing bytecodes which will most likely show the best performance on the JVM (which currently has no tail recursion optimization support (although that might change one day)).

I like it :-)

[update]
For reference, here’s a slightly more Scala-ish implementation of reduce, showing the same time performance characteristics during some basic profiling. I was not able to get JD nor jad to generate any usable decompiled code though:

def reduce[T, V](fun: (V, T) => V, values: List[T], initial: V): V = {
    values match {
        case List() => initial;
        case head :: tail => reduce(fun, tail, fun(initial, head))
    }
}

It uses Scala’s “List” pattern matching functionality.

]]>
http://eikke.com/scala-tail-recursion-decompiler/feed/ 7
Python if/else in lambda http://eikke.com/python-ifelse-in-lambda/ http://eikke.com/python-ifelse-in-lambda/#comments Sat, 16 Feb 2008 21:24:43 +0000 Nicolas http://eikke.com/python-ifelse-in-lambda/ Scott, in your “Functional Python” introduction you write:

The one limitation that most disappoints me is that Python lacks is a functional way of writing if/else. Sometimes you just want to do something like this:

lambda x : if_else(x>100, “big number”, “little number”)

(This would return the string “big number” if x was greater than 100, and “little number” otherwise.) Sometimes I get around this by defining my own if_else that I can use in lambda-functions:

def if_else(condition, a, b) :
   if condition : return a
   else         : return b

Actually, you don’t need this helper if_else function at all:

In [1]: f = lambda x: x > 100 and 'big' or 'small'
In [2]: for i in (1, 10, 99, 100, 101, 110):
...:     print i, 'is', f(i)
...:
1 is small
10 is small
99 is small
100 is small
101 is big
110 is big

James, obviously you’re right… Stupid me didn’t think about that. Your version won’t work when a discriminator isn’t known at import time. But even then a function taking *args and **kwargs with a class-like name, returning a correct class instance, would cut the job.

Regarding the module/plugin stuff, I’d rather use setuptools/pkg_resources :-)

]]>
http://eikke.com/python-ifelse-in-lambda/feed/ 17