Hide fields from deriving (Show) - haskell

Imagine I have a data record with many fields:
data DataRecord = DataRecord {
field1 :: String,
field2 :: String,
...
} deriving (Show)
Is it possible to hide some fields from the deriving (Show) or do have to implement my own show function for DataRecord?
Reason for my question: When I have cyclic dependencies between two data records both using deriving (Show) the show function would generate an infinite string.

The Haskell 2010 report mentions your cyclic dependencies as unsuitable case:
The derived Read and Show instances may be unsuitable for some uses. Some problems include:
Circular structures cannot be printed or read by these instances.
So you need to specify the instance by hand.

Related

Haskell possible make own type instance of Text

Noob here again. Getting my feet wet in making my own Haskell 'programs'. Stumbled across this.
Made my own type:
data Action = Action
{ idN :: IdN
, description :: Desc
, duedate :: Due
, donedate :: Done
} deriving (Ord, Show, Read, Eq)
Imported Data.Text.IO. Want to write concrete info in Action to file using
TIO.appendFile "./Dbase.txt" typedAction
where typedAction is the concrete representation of the Action type. Now Action is not of type Text.
So how would I go about this?

Multiple declaration error in data type declaration

I'm currently building a a Twitter CLI client in Haskell, and I have a data type that represents a DM and one that represents a tweet. However, I get a multiple declaration error because I have to use the same name for both:
data Users = Users { screen_name :: String } deriving(Show, Generic)
data Tweet = Tweet { text :: !Text,
retweeted :: Bool,
user :: Users
} deriving (Show, Generic)
data DM = DM { text :: !Text,
sender_screen_name :: String
} deriving (Show, Generic)
Does someone know a solution for this particular problem?
As defined here, the named members are just functions that are used to call the values in your data structure.
So, if you really want to use them, you can do so by using the language extension. You can do that by declaring this in your file:
{-# LANGUAGE DuplicateRecordFields #-}

How do I create several related data types in haskell?

I have a User type that represents a user saved in the database. However, when displaying users, I only want to return a subset of these fields so I made a different type without the hash. When creating a user, a password will be provided instead of a hash, so I made another type for that.
This is clearly the worst, because there is tons of duplication between my types. Is there a better way to create several related types that all share some fields, but add some fields and remove others?
{-# LANGUAGE DeriveGeneric #}
data User = User {
id :: String,
email :: String,
hash :: String,
institutionId :: String
} deriving (Show, Generic)
data UserPrintable = UserPrintable {
email :: String,
id :: String,
institutionId :: String
} deriving (Generic)
data UserCreatable = UserCreatable {
email :: String,
hash :: String,
institutionId :: String
} deriving (Generic)
data UserFromRequest = UserFromRequest {
email :: String,
institutionId :: String,
password :: String
} deriving (Generic)
-- UGHHHHHHHHHHH
In this case, I think you can replace your various User types with functions. So instead of UserFromRequest, have:
userFromRequest :: Email -> InstitutionId -> String -> User
Note how you can also make separate types for Email and InstitutionId, which will help you avoid a bunch of annoying mistakes. This serves the same purpose as taking a record with labelled fields as an argument, while also adding a bit of extra static safety. You can just implement these as newtypes:
newtype Email = Email String deriving (Show, Eq)
Similarly, we can replace UserPrintable with showUser.
UserCreatable might be a bit awkard however, depending on how you need to use it. If all you ever do with it is take it as an argument and create a database row, then you can refactor it into a function the same way. But if you actually need the type for a bunch of things, this isn't a good solution.
In this second case, you have a couple of decent options. One would be to just make id a Maybe and check it each time. A better one would be to create a generic type WithId a which just adds an id field to anything:
data WithId a = { id :: DatabaseId, content :: a }
Then have a User type with no id and have your database functions work with a WithId User.

Haskell: Creating record of list of string and pair of <string and list of string>

How to create a record of list of string and, pair of in Haskell
I tried the following
For creating a record of list of string
data testList = test [string]
deriving (Show, Eq)
When I run it, it gives me the following error
Not a data constructor: `test'
For creating a record of pair of
data testList = test (String,[string])
deriving (Show, Eq)
It also gives the same error
Not a data constructor: `test'
can anyone explain me the problem and solution for it.
The first letter of data types must be a capital letter.
wikipedia/haskell/type declarations

Haskell -- any way to qualify or disambiguate record names?

I have two data types, which are used for hastache templates. It makes sense in my code to have two different types, both with a field named "name". This, of course, causes a conflict. It seems that there's a mechanism to disambiguate any calls to "name", but the actual definition causes problems. Is there any workaround, say letting the record field name be qualified?
data DeviceArray = DeviceArray
{ name :: String,
bytes :: Int }
deriving (Eq, Show, Data, Typeable)
data TemplateParams = TemplateParams
{ arrays :: [DeviceArray],
input :: DeviceArray }
deriving (Eq, Show, Data, Typeable)
data MakefileParams = MakefileParams
{ name :: String }
deriving (Eq, Show, Data, Typeable)
i.e. if the fields are now used in code, they will be "DeviceArray.name" and "MakefileParams.name"?
As already noted, this isn't directly possible, but I'd like to say a couple things about proposed solutions:
If the two fields are clearly distinct, you'll want to always know which you're using anyway. By "clearly distinct" here I mean that there would never be a circumstance where it would make sense to do the same thing with either field. Given this, excess disambiguity isn't really unwelcome, so you'd want either qualified imports as the standard approach, or the field disambiguation extension if that's more to your taste. Or, as a very simplistic (and slightly ugly) option, just manually prefix the fields, e.g. deviceArrayName instead of just name.
If the two fields are in some sense the same thing, it makes sense to be able to treat them in a homogeneous way; ideally you could write a function polymorphic in choice of name field. In this case, one option is using a type class for "named things", with functions that let you access the name field on any appropriate type. A major downside here, besides a proliferation of trivial type constraints and possible headaches from the Dreaded Monomorphism Restriction, is that you also lose the ability to use the record syntax, which begins to defeat the whole point.
The other major option for similar fields, which I didn't see suggested yet, is to extract the name field out into a single parameterized type, e.g. data Named a = Named { name :: String, item :: a }. GHC itself uses this approach for source locations in syntax trees, and while it doesn't use record syntax the idea is the same. The downside here is that if you have a Named DeviceArray, accessing the bytes field now requires going through two layers of records. If you want to update the bytes field with a function, you're stuck with something like this:
addBytes b na = na { item = (item na) { bytes = b + bytes (item na) } }
Ugh. There are ways to mitigate the issue a bit, but they're still not idea, to my mind. Cases like this are why I don't like record syntax in general. So, as a final option, some Template Haskell magic and the fclabels package:
{-# LANGUAGE TemplateHaskell #-}
import Control.Category
import Data.Record.Label
data Named a = Named
{ _name :: String,
_namedItem :: a }
deriving (Eq, Show, Data, Typeable)
data DeviceArray = DeviceArray { _bytes :: Int }
deriving (Eq, Show, Data, Typeable)
data MakefileParams = MakefileParams { _makefileParams :: [MakeParam] }
deriving (Eq, Show, Data, Typeable)
data MakeParam = MakeParam { paramText :: String }
deriving (Eq, Show, Data, Typeable)
$(mkLabels [''Named, ''DeviceArray, ''MakefileParams, ''MakeParam])
Don't mind the MakeParam business, I just needed a field on there to do something with. Anyway, now you can modify fields like this:
addBytes b = modL (namedItem >>> bytes) (b +)
nubParams = modL (namedItem >>> makefileParams) nub
You could also name bytes something like bytesInternal and then export an accessor bytes = namedItem >>> bytesInternal if you like.
Record field names are in the same scope as the data type, so you cannot do this directly.
The common ways to work around this is to either add prefixes to the field names, e.g. daName, mpName, or put them in separate modules which you then import qualified.
What you can do is to put each data type in its own module, then you can used qualified imports to disambiguate. It's a little clunky, but it works.
There are several GHC extensions which may help. The linked one is applicable in your case.
Or, you could refactor your code and use typeclasses for the common fields in records. Or, you should manually prefix each record selector with a prefix.
If you want to use the name in both, you can use a Class that define the name funcion. E.g:
Class Named a where
name :: a -> String
data DeviceArray = DeviceArray
{ deviceArrayName :: String,
bytes :: Int }
deriving (Eq, Show, Data, Typeable)
instance Named DeviceArray where
name = deviceArrayName
data MakefileParams = MakefileParams
{ makefileParamsName :: String }
deriving (Eq, Show, Data, Typeable)
instance Named MakefileParams where
name = makefileParamsName
And then you can use name on both classes.

Resources