Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard placement of type declarations

Is there a standard for the location for type declarations in Haskell?

For example, suppose I have two functions:

abs' x = if x >= 0 then x else -x

pow x 0 = 1
pow x e = x * (pow x (e-1))

and their type declarations are:

abs' :: Int -> Int
pow :: Int -> Int -> Int

Is it more appropriate/readable to place the declarations at the top of the file, like such:

abs' :: Int -> Int
pow :: Int -> Int -> Int

abs' x = if x >= 0 then x else -x

pow x 0 = 1
pow x e = x * (pow x (e-1))

Or to place each above its respective function, as in:

abs' :: Int -> Int
abs' x = if x >= 0 then x else -x

pow :: Int -> Int -> Int
pow x 0 = 1
pow x e = x * (pow x (e-1))

Either way seems perfectly viable to me, so I was wondering if there was any standard for this. Also, supposing these are in a module, does their accessibility from the outside world affect the placement of their type declarations?

like image 831
mjgpy3 Avatar asked Apr 13 '13 06:04

mjgpy3


1 Answers

The most common style is to put type signatures directly above the function, regardless of whether it gets exported or not.

It's easier to modify and update functions if everything is close together. It also helps to have the type signature and function together when reading the code--this way you don't have to look up the signature in a different part of the file or remember it.

The alternate style you proposed would be better for getting a summary of a module. Happily, we can very easily do this with the :browse command in GHCi:

*Main> :browse Data.Function
Data.Function.fix :: (a -> a) -> a
Data.Function.on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
($) :: (a -> b) -> a -> b
(.) :: (b -> c) -> (a -> b) -> a -> c
const :: a -> b -> a
flip :: (a -> b -> c) -> b -> a -> c
id :: a -> a

So the style of putting all the signatures at the top does not really have much to recommend it and isn't used.

like image 73
Tikhon Jelvis Avatar answered Nov 03 '22 21:11

Tikhon Jelvis