This is a coding style question rather then a technical one.
I have frequently encountered a problem where I use haskell's (less then optimal) record syntax (or lenses, the problem ends up the same) to create a data
type. I end up with field accessor functions named after my fields. Being a conscientious programmer, I try to make my record field names meaningful.
At some point later I need to get a field out of my type and keep its value in a local variable. This is often done within a StateMonad in a do
block. The question is what do I call the local variable. The most obvious name is already taken as the field accessor. I find my self using abbreviations which tends to make my code less readable.
Is there a Haskell coding convention that addresses this issue?
Example
data Qaax = Qaax {
foo :: SomeFoo
, bar :: SomeBar
, ...
}
baz :: (MonadState Qaax m) => (...) -> m ()
baz (...) = do
f <- gets foo -- I'd really like to use something more descriptive then
-- `f` but `foo` is already taken.
...
return ()
The NamedFieldPuns
extension can help with this. When pattern-matching on a record, it binds a variable with the same name as a record field:
{-# LANGUAGE NamedFieldPuns #-}
baz :: (MonadState Qaax m) => m ()
baz = do
Qaax {foo} <- get
return ()
One possible problem is that the accessor is shadowed for the rest of the do
block.
Adding ' as a suffix is an established convention for forming distinct-but-related names. A key example is foldl
and foldl'
.
In exported names like foldl'
it's usually a good idea to come up with a consistent theme for what the ' means for your library (often it's "stricter version of", as in foldl'
). But in local names you can be a lot freer to just use it "another closely related thing I would like to have the same name as".
The downside is that it's not very distinct, so it can hurt readability; especially if you need to commonly refer to both versions. And when you find yourself needing foo'''
you should probably think about a different naming scheme!
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