Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Principles, Best Practices and Design Patterns for functional programming

Tags:

Are there any known principles, best-practices and design patterns that one can follow while writing code in a functional programming language?

like image 350
amit-agrawal Avatar asked May 08 '09 22:05

amit-agrawal


2 Answers

There are folds, unfolds, maps, etc.

I consider using them best practice, as it is pretty easy to reason about their behavior, and they often communicate the purpose of a function (for an example, just take a look at the famous Evolution of a Haskell Programmer and contrast freshman with senior, and with professor).

like image 191
fishlips Avatar answered Nov 16 '22 22:11

fishlips


Design pattern: let types guide your coding.

  1. Figure out what type you are trying to return.

  2. Know that certain type constructors come with certain syntax, and exploit it to make the desired type smaller. Here are two examples:

    • If you are trying to return a function type T1 -> T2, it is always safe to write

      \ x -> ... 

      Now in the body you are trying to produce a value of type T2, which is a smaller type, plus you have gained an extra value x of type T1, which may make your job easier.

      If the lambda turns out to be unnecessary, you can always eta-reduce it away later.

    • If you are trying to produce a pair of type (T1, T2), you can always try to produce a value x of type T1 and a value y of type T2, then form the pair (x, y). Again, you've reduced the problem to one with smaller types.

  3. Once the types are as small as you can make them, look at the types of all the let-bound and lambda-bound variables in scope, and see how you can produce a value of the type you want. Typically you expect to use all arguments to all functions; if you don't, be sure you can explain why.

In many situations, especially when writing polymorphic functions, this design technique can reduce the construction of a complicated function down to just one or two choices. The types guide the construction of the program so that there are very few ways to write a function of the correct type---and usually only one way that is not obviously wrong.

like image 33
Norman Ramsey Avatar answered Nov 16 '22 22:11

Norman Ramsey