9

Can someone point me to examples of multiparadigm (object-functional) programming in F#?

I am specifically looking for examples which combine OO & functional programming. There's been a lot of talk about how F# is a hybrid language but I've not been able to find examples which demonstrate the example of multiparadigm programming.

Thanks

SharePoint Newbie
  • 5,974
  • 12
  • 62
  • 103
  • Is not the fact that F# can *consume* and *produce* class types which can be used by other MSIL languages (e.g. C#, VB.NET and J#) enough to argue for the "object" aspect? Or is there a more specific inquiry lurking? –  Nov 06 '10 at 19:25
  • What do you really want? It sounds kinda like you're asking for a real-world 10,000-line example (perhaps backed by a case-study whitepaper); if not, can you clarify what you want to see? – Brian Nov 06 '10 at 22:07
  • 1
    Hi, I just wanted to see the advantages of object-functional programming over just OO or functional programming alone. I've been using F# and C# both on a project but F# mainly for writing library methods consumed by C#. We are looking for examples of how hybrid programming can help us. As of now we only use pattern matching and list comprehensions (within methods only). Clearly there should be more to it which we are missing :) – SharePoint Newbie Nov 07 '10 at 06:47
  • Functional programming adds higher order functions and makes it easier to program without mutation. F# has it's own useful list of features such as Discriminated Unions, Active Patterns, Pattern matching, Units of Measure, Async programming and much more. F# also has it's own style of OO because of the way it's default constructor is handled and how `let` is private. The use of `Option` also changes the OO style some. – gradbot Nov 11 '10 at 22:44
  • 1
    Note that you don't need to look at F# to see this. C# code that uses the Task Parallel Library's `Parallel.For` higher-order function in .NET 4 is a compelling example from the mainstream. – J D Dec 31 '10 at 23:16

5 Answers5

10

I made a small (600 lines) Tetris clone with F# that is Object Oriented using XNA. The code is old (uses #light) and isn't the prettiest code you will ever see but it's defiantly a mix of OOP and functional. It consists of ten classes. I don't think I pass any first class functions around but it's a good example of the F#'s functional power in programming the small.

  • MyGame - Inherits XNA main game class and is the programs entry point.
  • Board - Keeps track of pieces that are no longer moving and horizontal line completes.
  • UI - The UI only has two states (playing and main menu) handled by bool stateMenu
  • Tetris - Handles game state. Game over and piece collision.
  • Piece - Defines the different Tetris shapes and their movement and drawing.
  • Player - Handles user input.
  • Shape - The base graphic object that maps to primative.
  • Primative - Wraps the Vertex primitive type.

I made a rough class diagram to help. If you have any questions about it feel free to ask in the comment section.

alt text

gradbot
  • 13,732
  • 5
  • 36
  • 69
  • Very nice answer, I had no idea XNA and F# would have such awesome functionalities together, I didn't even know it was suppported for that at all ( Stop laughing :P) – Proclyon Nov 18 '10 at 12:07
6

There are two ways of combining the functional and object-oriented paradigm. To some extent, they are independent and you can write immutable (functional) code that is structured using types (written as F# objects). An F# example of Client type written like this would be:

// Functional 'Client' class
type Client(name, income) =
  // Memebers are immutable
  member x.Name = name
  member x.Income = income

  // Returns a new instance 
  member x.WithIncome(ninc) =
    new Client(name, ninc)
  member x.Report() =
    printfn "%s %d" name income

Note that the WithIncome method (which "changes" the income of the client) doesn't actually do any modifications - it follows the functional style and creates a new, updated, client and returns it as the result.

On the other hand, in F# you can also write object-oriented code that has mutable public properties, but uses some immutable data structure under the cover. This may be useful when you have some nice functional code and want to expose it to C# programmers in a traditional (imperative/object-oriented) way:

type ClientList() =
  // The list itself is immutable, but the private
  // field of the ClientList type can change
  let mutable clients = []
  // Imperative object-oriented method
  member x.Add(name, income) =
    clients <- (new Client(name, income))::clients
  // Purely functional - filtering of clients
  member x.Filter f = 
    clients |> List.filter f

(The example is taken from the source code of Chapter 9 of my book. There are some more examples of immutable object-oriented code, for example in parallel simulation in Chapter 14).

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • Thanks. I have not been able to find any motivation for writing object-functional code. I've mostly been doing immutable objects like you've mentioned. However, are there any cases where mutable object state and a object hierarchy with mutable data helps in a language like F#? I am specifically looking for examples where object-functional programming is better than functional and OO independently. – SharePoint Newbie Nov 07 '10 at 06:39
  • 2
    I've read your book and also a couple of F# books. Most of the examples are either functional or oo but don't show any real advantages of mixing OO and functional programming. – SharePoint Newbie Nov 07 '10 at 06:40
4

The most powerful experience I've had mixing OO (specifically mutation) and functional programming is achieving performance gains by using mutable data-structures internally while enjoying all the benefits of immutability by external users. A great example is an implementation I wrote of an algorithm which yields lexicographical permutations you can find here. The algorithm I use is imperative at it's core (repeated mutation steps of an array) which would suffer if implemented with a functional data structure. By taking an input array, making a read-only copy of it initially so the input is not corrupted, and then yielding read-only copies of it in the sequence expression after the mutation steps of the algorithm are performed, we strike a fine balance between OO and functional techniques. The linked answer references the original C++ implementation as well as benchmarks other purely functional implementation answers. The performance of my mixed OO / functional implementation falls in between the superior performance of the OO C++ solution and the pure functional F# solution.

This strategy of using OO / mutable state internally while keeping pure externally to the caller is used throughout the F# library notably with direct use of IEnumerators in the Seq module.

Another example may be found by comparing memoization using a mutable Dictionary implementation vs. an immutable Map implementation, which Don Syme explores here. The immutable Dictionary implementation is faster but no less pure in usage than the Map implementation.

In conclusion, I think using mutable OO in F# is most powerful for library designers seeking performance gains while keeping everything pure functional for library consumers.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Stephen Swensen
  • 22,107
  • 9
  • 81
  • 136
3

I don't know any F#, but I can show you an example of the exact language mechanics you're looking for in Scala. Ignore it if this isn't helpful.

class Summation {

    def sum(aLow : Int, aHigh : Int) = {
        (aLow to aHigh).foldLeft(0) { (result, number) => result + number }
    }

}

object Sample {

    def main(args : Array[String]) {
        println(new Summation sum(1, 10))
    }

}

I tried to keep it super simple. Notice that we're declaring a class to sum a range, but the implementation is used with a functional style. In this way, we can abstract the paradigm we used to implement a piece of code.

Mike
  • 19,267
  • 11
  • 56
  • 72
  • I dunno if that's really an example, though. Sure, you're using `object`, but you're not using any of its power. Just as a way to hold a method, which is never called except by the runtime. – Antal Spector-Zabusky Nov 06 '10 at 18:32
  • Thanks for the example Mike. But there's no OO involved here. Would it be possible for you to point me to something which offers the advantages of both OO and funct programming and has advantages compared to bith these approaches independently? – SharePoint Newbie Nov 06 '10 at 18:49
  • Yeah, perhaps a little too simple. I adjusted a little bit. If this still doesn't suffice, let me know. Also might help to mention that I'm not very good at Scala. – Mike Nov 06 '10 at 19:02
2

I don't know about F#, but most softwares written in Scala are object-functional in nature.

Scala compiler is probably the largest and a state of the art example of an object-functional software. Other notable examples include Akka, Lift, SBT, Kestrel etc. (Googling will find you a lot more object-functional Scala examples.)

missingfaktor
  • 90,905
  • 62
  • 285
  • 365