Final thoughts on Miranda and FP
Constructors are functions
A type constructor is really just a special kind of function:
expr ::= NumExpr num | CharExpr char NumExpr:: num->expr Contrast this with Java, where constructors have special semantics.
Functional style
Functional style can be very powerful and useful even in non-functional languages. Many people believe that functional style leads to clearer, more concise, and more flexible programs. Elements of functional style:
- Avoid side effects: instead, compute and return values. Prefer return values to output parameters.
- First class functions: consider passing functions instead of, or in addition to, data. Parameterize algorithms with functions for flexibility. In languages without first-class functions, use function pointers, functors, or interfaces.
- Lazy evaluation: Do not compute a value until you need it. "Pull" values through a system rather than "pushing" them. While not always appropriate, lazy evaluation can sometimes be a useful technique.
- Polymorphic types: C++ templates and other language mechanisms for "generic" or "parameterized" types are essentially forms of polymorphism. Thinking of operations as polymorphic functions that work with multiple types can lead to more reusable code.
- Decomposition: functional programs are often constructed by composing many small functions rather than a few large procedures, because functional languages provide powerful and simple ways to compose functions. Think of ways to decompose systems into small pieces, often with a recursive structure, so that your code modules each become small and manageable.