Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 9 Next »

Functional programming is a style of programming that emphasizes the application of functions to solve computing problems. This is in contrast with imperative programming, which emphasizes changes in state and the execution of sequential commands. If you want use a functional-only programming language, you should consider something like Haskell. If however you like Groovy but want to apply some functional style magic, read on.

Functional Basics

Groovy's functions (like Java's) can be used to define functions which contain no imperative steps, e.g. a factorial function may look like:

In Groovy, we gain some slight syntactic sugar over Java in that we can leave out the return statements.

We can of course start to mix and match functional and imperative coding styles:

Curry functions

You can fix the values for one or more arguments to a closure instance using the curry() method as follows:

If you supply one argument to the curry() method you will fix the first argument. If you supply N arguments you will fix arguments 1..N. See reference 1 or Chapter 5 of GINA for further details.

Infinite structures

See reference 2 below for all the details, but to give you a flavour, first you must define some lazy list handling functions, then you can define and use infinite streams. Here is an example:

More Information

See also:

  1. Practically Groovy: Functional programming with curried closures
  2. Infinite Streams in Groovy
  3. Functional Programming Languages
  4. Why Functional Programming Matters
  5. Functional programming in the Java language
  6. Post on functional programming in Java - maybe a tad verbose
  7. FunctionalJ - A library for Functional Programming in Java
  • No labels