3 ms·
Personally, I write the type signature before I write the function implementing it. It is a nice thing to look at as you are writing the function; it keeps you
by jrockway 17y ago
Personally, I write the type signature before I write the function implementing it. It is a nice thing to look at as you are writing the function; it keeps you focused on what to do. Oh, and it is great documentation, that the compiler ensures is up to date -- if your function does something the type signature disagrees with, your program won't compile. Excellent!
One other thing I do, which is maybe not as common, is liberally using "type" aliases. Instead of:
connectToDatabase :: String -> String -> String -> IO DatabaseHandle
I would write:
type Dsn = String
type Username = String
type Password = String
connectToDatabase :: Dsn -> Username -> Password -> IO DatabaseHandle
Self-documenting. (The type declarations also let you hang haddock documentation off them; good if you are using that type in more than one function. Then instead of documenting what a "Password" is everywhere you have a Password, you can just document it at the type declaration. Time-saving!)
As an aside, I could also get type safety by using "newtype" instead of "type". For something this simple, though, I find the flexibility of being able to use any old String to be rather useful; ``connectToDatabase (mkDsn "MySQL:foobar") (mkUsername "jrockway") (mkPassword "OH HAI")'' is a bit verbose, after all.
(I am also usually too lazy to derive Monad, MonadError, MonadWrite, and MonadIO instances for things like "type MyAction = ReaderT String (WriterT [String] (ErrorT String IO))", so I use type instead of newtype.)
- anamax 17y ago> Personally, I write the type signature before I write the function implementing it. It is a nice thing to look at as you are writing the function; it keeps you focused on what to do. Oh, and it is great documentation, that the compiler ensures is up to date -- if your function does something the type signature disagrees with, your program won't compile. Excellent! That partitions the function definition. And it's optional. And it could be somewhere else. And you get to argue with folks who like point-free because it's shorter.