Difference between revisions of "Parameter order"

From HaskellWiki
Jump to navigation Jump to search
m
Line 61: Line 61:
 
----
 
----
   
There are also bad examples, e.g. the functions from <hask>Data.Bits</hask>. See [[SyntacticSugar/Cons]].
+
There are also bad examples, e.g. the functions from <hask>Data.Bits</hask>. See [[syntactic sugar/Cons |Cons of syntactic sugar]].
   
   

Revision as of 19:58, 13 October 2006

The parameter order of Haskell functions is an important design decision when programming libraries. The parameter order shall

  • allow piping,
  • be consistent across similar functions.

Parameters in Haskell are rather reversed compared to imperative or object oriented languages. In an object oriented language, the object to work on is the very first parameter. In a function call it is often written even before the function name, say file in file.write("bla"). Strictly spoken, in Haskell it is not possible to alter objects, but there are many functions which return a somehow altered input object. This object should be the last parameter because then you can compose a sequence of operations on this object using the function composition operator .. The code

sum . map f . filter p . scanl (*) 1

describes a function, which applies three transformations to a list. This can be written so easily because the list is always the last parameter.

The order of the parameters except the last one is not so critical. However you should keep in mind that also transformations on functions are perfectly ok in Haskell. That's why function operators like the differentiation and integration in functional analysis should have the parameter of the derived/integrated function at the last position and the transformed function should be the parameter before the last one.

integrate :: a -> (a -> a) -> (a -> a)
integrate f0 f x = ...

differentiate :: a -> (a -> a) -> (a -> a)
differentiate h f x = ...

-- continuous extension, aka function limit
continuous :: (a -> a) -> (a -> a)
continuous f x = ...

exampleTransform = differentiate h . continuous


The third thing to consider is that it is easily possible to fix parameters, which are at the beginning. E.g.

sum = foldl (+) 0
product = foldl (*) 1

that's why we can consider the parameter order of foldl to be a good one. We also see in this example that it is easily possible to generate a function with the first parameters fixed and that functions shall be prepared for this.


The rule of thumb

What do we learn from all this considerations?

The more important the parameter, the more frequently it changes, the closer shall it be at the end of the parameter list. If there is some recursion involved, probably the parameter, on which you recurse, is the one which should be at the last position.



There are also bad examples, e.g. the functions from Data.Bits. See Cons of syntactic sugar.