C++0x (C++11) as functional language? - c++

i'm wondering if C++0x (C++11) (with lambdas and perfect forwarding) is (a superset of) a functional language.
is there any feature of functional languages, that C++ doesn't have?

The functional programming paradigm models computation as a relation between sets, and is thus inherently declarative. However, in practice, we often think of functions as imperative, ie you put in an input value and get out an output value, same as with a procedure. From this point of view, the characteristic property of a function is that it has no side-effects. Because of ambiguity of the terms, we call such a function pure, and a language which only has pure functions would be a purely functional language.
However, not all functional languages are pure: A functional language is a language with syntax and semantics which allows the programmer to use the functional paradigm efficiently. Some of the concepts which make using the paradigm feasible include - among others - lambda expressions with lexical closure, higher-order functions, variant types and pattern matching, lazy evaluation, type-inference (in case of statically-typed languages).
This is by no means an authorative list, and a language can very well be functional without providing all or even most of them, but if a language does - ie makes them usable without having to jump through major hoops - their presence is a strong indicator that the language should be considered functional.
I don't know enough about Boost to decide whether or not C++03 + Boost is a viable functional language, but C++0x definitely makes C++ more functional, perhaps even pushing it over the subjective boundary of the realm of functional languages.
As an aside, the same considerations apply to other programming paradigms: C++ is also not a purely object-oriented language (indeed, it's very hard - perhaps even theoretically impossible - to design a language which is both purely functional and purely object-oriented), and most features one commonly associates with OO-languages (classes, inheritance, encapsulation) are actually in no way authorative as well...

Check out the list of Functional Programming Languages definitions and discussion on the C2 wiki.
Some of the most common (and least disputed features) are:
First class functions - function class represents first class functions.
Higher Order Functions - Can be emulated with function objects.
Lexical Closures - Can be emulated with classes.
Single Assignment - More of a convention. You can do this by declaring all variables const.
Lazy Evaluation - Can be achieved with TMP
Garbage Collection - still missing. Pretty much necessary in a functional language, since lifetime and scope are not the same, as #Pascal pointed out in the comments above.
Type Inference - auto
Tail Call Optimization - Not strictly necessary for a functional language, but compiler dependent in C++.

Related

variants, existential polymorphism in c++

I am conducting a research on type systems. For this work I am investigating the usages of Variants, structural subtyping, universal polymorphism and existential polymorphism in popular languages. Functional languages like heskell, ocaml provides such functionaries. But I want to whether a popular language like C++ provide above functionality. That means how C++ implemented
variants
structural subtyping
universal polymorphism
existential polymorphism.
Unions can be viewed as a rudimentary form of variant, but in reality, they are more a primitive mechanism for overlaying memory (and unsafe).
There is no structural typing, let alone subtyping, in C++. All types are nominal.
Templates have some superficial similarity to universal polymorphism, but are actually quite different. In essence, they are glorified macros with little to no type checking (like with macros, both checking and code generation happens after expansion).
There is no form of existential types in C++ (there is a limited form in Java, namely wildcards).
Some of these features can be simulated to some extent using subtyping, but that remains far less expressive (or convenient).

Why were concepts (generic programming) conceived when we already had classes and interfaces?

Also on programmers.stackexchange.com:
I understand that STL concepts had to exist, and that it would be silly to call them "classes" or "interfaces" when in fact they're only documented (human) concepts and couldn't be translated into C++ code at the time, but when given the opportunity to extend the language to accomodate concepts, why didn't they simply modify the capabilities of classes and/or introduced interfaces?
Isn't a concept very similar to an interface (100% abstract class with no data)? By looking at it, it seems to me interfaces only lack support for axioms, but maybe axioms could be introduced into C++'s interfaces (considering an hypothetical adoption of interfaces in C++ to take over concepts), couldn't them? I think even auto concepts could easily be added to such a C++ interface (auto interface LessThanComparable, anyone?).
Isn't a concept_map very similar to the Adapter pattern? If all the methods are inline, the adapter essentially doesn't exist beyond compile time; the compiler simply replaces calls to the interface with the inlined versions, calling the target object directly during runtime.
I've heard of something called Static Object-Oriented Programming, which essentially means effectively reusing the concepts of object-orientation in generic programming, thus permitting usage of most of OOP's power without incurring execution overhead. Why wasn't this idea further considered?
I hope this is clear enough. I can rewrite this if you think I was not; just let me know.
There is a big difference between OOP and Generic Programming, Predestination.
In OOP, when you design the class, you had the interfaces you think will be useful. And it's done.
In Generic Programming, on the other hand, as long as the class conforms to a given set of requirements (mainly methods, but also inner constants or types), then it fits the bill and may be used. The Concept proposal is about formalizing this, so that detection may occur directly when checking the method signature, rather than when instantiating the method body. It also makes checking template methods more easily, since some methods can be rejected without any instantiation if the concepts do not match.
The advantage of Concepts is that you do not suffer from Predestination, you can pick a class from Library1, pick a method from Library2, and if it fits, you're gold (if it does not, you may be able to use a concept map). In OO, you are required to write a full-fledged Adapter, every time.
You are right that both seem similar. The difference is mainly about the time of binding (and the fact that Concept still have static dispatch instead of dynamic dispatch like with interfaces). Concepts are more open, thus easier to use.
Classes are a form of named conformance. You indicate that class Foo conforms with interface I by inheriting from I.
Concepts are a form of structural and/or runtime conformance. A class Foo does not need to state up front which concepts it conforms to.
The result is that named conformance reduces the ability to reuse classes in places that were not expected up front, even though they would be usable.
The concepts are in fact not part of C++, they are just concepts! In C++ there is no way to "define a concept". All you have is, templates and classes (STL being all template classes, as the name says: S tandard T emplate L ibrary).
If you mean C++0x and not C++ (in which case I suggest you change the tag), please read here:
http://en.wikipedia.org/wiki/Concepts_(C++)
Some parts I am going to copy-paste for you:
In the pending C++0x revision of the C++ programming language, concepts and the related notion of axioms were a proposed extension to C++'s template system, designed to improve compiler diagnostics and to allow programmers to codify in the program some formal properties of templates that they write. Incorporating these limited formal specifications into the program (in addition to improving code clarity) can guide some compiler optimizations, and can potentially help improve program reliability through the use of formal verification tools to check that the implementation and specification actually match.
In July 2009, the C++0x committee decided to remove concepts from the draft standard, as they are considered "not ready" for C++0x.
The primary motivation of the introduction of concepts is to improve the quality of compiler error messages.
So as you can see, concepts are not there to replace interfaces etc, they are just there to help the compiler optimize better and produce better errors.
While I agree with all the posted answers, they seem to have missed one point which is performance. Unlike interfaces, concepts are checked in compile-time and therefore don't require virtual function calls.

C++, the term/idiom for programming using template

I keep reading the term :
template programming
generic programming
meta-programming
maybe another idiom/term..
for any c++ code that use template, which one is the correct or more accurate term of this?
AFAIK:
Template programming is just referring to the classic "programming with templates", i.e. "I have a function/class that I want to make usable with any type, I'll just make it template".
It can also be can also be seen as the "catch-all" category that includes any programming technique that employs templates.
Generic programming can be synthetically described as the programming paradigm used by the STL.
Wikipedia defines it as
a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters
IMHO, it's better to say that all the containers are designed to be used with any type (without sacrificing type safety) and algorithms are designed to be generic enough to work on any container type (as long as it's sensible to use them, obviously, i.e. it makes no sense to sort an unordered container).
Notice that generic programming (with this definition) does not strictly require the use of templates, in facts it can be achieved with inheritance and dynamic polymorphism (thanks to Ben Voigt).
In general, I'd say that template programming and generic programming partially overlap, and many people use the terms generic programming and template programming interchangeably.
Template metaprogramming is a programming style in which templates are used to perform compile-time computations/decisions/checks normally not doable without templates (statical assertions, compile-time constants computations, ...).
Such code is often quite contrived, since C++ wasn't designed for this style of programming (which was actually "discovered" later), and may look unfamiliar to C++ programmers also because it often gets near to functional programming (without having nice syntax facilities for it) instead of following the imperative paradigm normally used in C++.
It's usually referred to as generic programming.
Template meta programming is something else than normal use of templates, in TMP types are manipulated at compile time (see boost.Mpl).

Functional Programming and Type Systems

I have been learning about various functional languages for some time now including Haskell, Scala and Clojure. Haskell has a very strict and well-defined static type system. Scala is also statically typed. Clojure on the other hand, is dynamically typed.
So my questions are
What role does the type system play in a functional language?
Is it necessary for a language to have a type system for it to be functional?
How is the "functional" level of a language related to the kind of the type system of the language?
A language does not need to be typed to be functional - at the heart of functional programming is the lambda calculus, which comes in untyped and typed variants.
The type system plays two roles:
it provides a guarantee at compile time that a class of errors cannot occur at run-time. The class of errors usually includes things like trying to add two strings together, or trying to apply an integer as a function.
it has some efficiency benefits, in that objects at runtime do not need to carry their types around, because the types have already been established at compile-time. This is known as type erasure.
In advanced type systems like Haskell's, the type system can provide more benefits:
overloading: using one identifier to refer to operations on different types
it allows a library to automatically choose an optimised implementation based on what type it is used at (using Type Families)
it allows powerful invariants to be proven at compile time, such as the invariant in a red-black tree (using Generalised Algebraic Datatypes)
What role does the type system play in a functional language?
To Simon Marlow's excellent answer, I would add that a type system, especially one that includes algebraic data types, makes it easier to write programs:
Software designs, which in object-oriented languages are sometimes expressed using UML diagrams, are very clearly expressed using types. This clarity manifests especially when not only values have types, but also modules have types, as in Objective Caml or Standard ML.
When a person is writing code, a couple of simple heuristics make it very, very easy to write pure functions based on the types:
A value of function type can always be created with a lambda.
A value of function type can always be consumed by applying it.
A value of an algebraic data type can be created by applying any of the type's constructors.
A value of an algebraic data type can be consumed by scrutinizing it with a case expression.
Based on these observations, and on the simple rule that unless there's a good reason, a function should consume each of its arguments, it's pretty easy to cut down the space of possible code you could write to a very small number of candidates. For example, there just aren't that many sensible functions of type (using Haskell notation)
forall a . (a -> Bool) -> [a] -> Bool
The art of using types to create code is called type-directed programming. When it works well, you hear functional programmers say things like "once we got the types right, the code practically wrote itself." Since the types are usually much smaller than the
code, this is a big win.
Same as in any programming language: it helps you to avoid/find errors in your code. In case of static typing a good type system prevents programs with certain types of errors from compiling.
No. The untyped lambda calculus is what you could call the prototype of functional programming languages and it is, as the name suggests, entirely untyped.
In a functional language (as well as any other language where a function can be used as a value) the type system needs to know what the type of a function is. Other than that there is nothing special about type systems for functional languages.
In a purely functional language you need to abstract side-effects, so you'd want the type system to somehow be able to support that. For example if you want to have a world type like in Clean, you'd want the type system to support uniqueness types to ensure proper usage.
If you want to have an IO monad like in haskell, you'd need an IO type (though a monad typeclass like in haskell is not required to have an IO monad, so you don't need a type system, which supports that).
1: Same as any other, it stops you from doing operations that are either ill-defined, or whose result would be 'nonsensical' to humans. Like float addition on integers.
2: Nope, the oldest programming language in the world, the (untyped) lambda calculus, is both functional and untyped.
3: Hardly, functional just means no side effects, no mutations, referential transparency et cetera.
Just remember that the oldest functional language, the untyped lambda calculus has no type system.

Is C++ not a fully OOP Language?

I know that in OOP we have to declare everything e.g. variables, functions, etc. inside a class like in Java, but in C++ we can declare outside the class too.
Is this the reason that, C++ is not fully OOP? Or is there anything else?
Huh? C++ is a hybrid, multi-paradigm language. It is certainly not a "pure" object-oriented language, where "everything is an object" holds true. C++ supports classes, objects, encapsulation, and so on, but since it's also (more or less) backwards-compatible with a lot of C code, it cannot be "fully object-oriented".
Object-Oriented Programming is not definition of the language, it's definition of the programming, a program. I.e. one program in C++ can be OOP, and other can be not OOP.
What you can say is that C++ fully supports means of programming in OOP paradigm.
Define fully OOP? There are as many opinions as people probably
Note as far as purity goes, IIRC all languages with valuetypes are not "pure" in the strict sense. No, boxing doesn't count.
Over the years, in discussion I've tried to go back to the core OOP features:
identity
Classification
polymorphism (not inheritance, since some OOP have no inheritance)
encapsulation
So if you can tell if two classes are not the same class (identity), you can make the classic "duck quacks" and "dog barks" example (to demonstrate inheritance/polymorphism and classification) and you can hide fields, you are pretty much there.
Applying it to all the languages is more difficult though. While I do get functional programming roughly, I'm not trained enough in the their near infinite jargon to judge all those functional-oop-imperative hybrids that are springing up,
In C++ you don't HAVE to code using OOP, you can choose not to use it. Having said that, it's "fully OOP", OOP is just just not a requirement.
not even java is a full OOP language.
in real OOP languages everything is an object, conditionals, loops, etc.
Even though the question is somewhat ugly phrased I'm not really satisfied with all the answers provdided yet.
I preffer to think of languages as "supporting a paradigm" and not "being in a paradigm".
So, when does a language support a paradigm? When it is easy to write code that satisifies the requirements of the paradigm.
How one comes to this conclusion? Consider the style linux filesystems are implemented. It is C-Code that clearly has OO properties. So, would you not consider this code to be OOP because C is not a OOP-language? I don't think so. (I guess some people will rightfully disagree as this seems to be amtter of opinion.)
What does this imply for C++? Well, C++ has a lot of facilities for making it easier to program in a OO-Style, but it also provides you with a lot of means to rape the paradigm and write code that looks OO (because you use classes, inheritance private variables) but completly violates some other OO-principles (e.g. single responsibility, open-closed, uniform access).
I would conclude that C++ supports the OO-paradigm to some extent but is clearly inferior to some of the modern OO languages.
The main concept of OOP is that every member in an object oriented programming language should be defined inside of the class, whereas in c++ the main function is defined outside of a class. That is why c++ is not fully object oriented programming language.
The main() function is not inside a class, so for this reason, one could argue that C++ is not fully OOP.
One of the reason C++ is not fully OOP is the requirement of backward compatibility with a lot of C code. Built in types are not Objects in C++ as it is less efficient if they were. Remember, C++ first target audience were existing C programmers and efficiency was (is) a great concern.
However, C++ supports all the important features of OOP.
Related Link : www.research.att.com/~bs/oopsla.pdf