Principles, Best Practices and Design Patterns for functional programming

后端 未结 7 1646
我在风中等你
我在风中等你 2021-01-31 09:56

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

7条回答
  •  一个人的身影
    2021-01-31 10:40

    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.

提交回复
热议问题