Are there any known principles, best-practices and design patterns that one can follow while writing code in a functional programming language?
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).
Design pattern: let types guide your coding.
Figure out what type you are trying to return.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With