What does a very general function look like in functional programming?
Somebody said “we don’t have objects, but we have higher order functions”. Do higher order functions replace objects?
While programming object-oriented apps, I try to go from a more general to a more detailed idea, lots of times. If I try to do that in functional programming, am I going to need lots of higher order functions?
This answer is oriented towards Haskell rather than Lisp because although lisp has higher order functions, idiomatic lisp can be and is often very object-oriented.
We’ll also ignore inheritance (and ad-hoc polymorphism) which is commonly associated with object oriented programming, but is somewhat orthogonal.
In general, abstract data types “replace” objects, in the sense that generally you use an object to bundle together a bunch of related data in e.g. Java or Python, and you declare a data type to do such a thing in Haskell or ML.
However objects also bundle behavior with the data. So an object of a class has data, but also functions which can access and mutate that data. In a functional style, you’d simply declare the functions on your data type outside of that data type. Then encapsulation is provided by either modules or use of closures.
On the latter point — closures and objects are duals, although it is not necessarily idiomatic to express them as such. There’s some very old-school discussion of this at the portland patterns wiki: http://c2.com/cgi/wiki?ClosuresAndObjectsAreEquivalent.
Oh, and an example from oleg: http://okmij.org/ftp/Scheme/oop-in-fp.txt.
Ignoring typeclasses (which are essential to idiomatic Haskell), and focusing just on core functional programming, here’s a sketch of a different approach to something that would be done with inheritance in an OO language. Function foo uses some object that implements interface A and some object that implements interface B to produce some Double. With higher order functions, you’d perhaps have a type signature of
fooGen :: (a -> Double -> Double) -> (b -> String -> Double) -> a -> b -> Double.That signature says that
fooGentakes a function from some a and a Double to another Double, and a function of some b and a String to a Double, and then it takes an a and a b, and finally it returns a Double.So now you can pass in the “interface” separately from the concrete values through partial application, by declaring, e.g.,
fooSpecialized = fooGen funcOnA funcOnB.With typeclasses, you can abstract away the concrete passing in of the “interface implementation” (or, in more proper language, dictionary), and declare
foo :: HasSomeFunc a, HasSomeOtherFunc b => a -> b -> Double. You can think of the stuff on the left hand side of the=>as declaring, loosely, the interfaces that your concrete a and b types are required to implement.This is all a handwavy and partial answer of course to an exceedingly general question.