Haskell possible make own type instance of Text - haskell

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?

Related

Is there an idiomatic way to do deal with this situation when two structures share some content?

I'm making a toy forum to gain familiarity with Haskell and Servant.
My API looks something like this:
type UserAPI = "messages" :> ReqBody '[JSON] Msg :> Header "X-Real-IP" String :> Post '[JSON] APIMessage
:<|> "messages" :> ReqBody '[JSON] Int :> Get '[JSON] [Msg']
My types look something like this:
data Msg = Msg
{ thread :: Int
, dname :: String
, contents :: String
} deriving (Eq, Show, Generic)
data Msg' = Msg'
{ thread' :: Int
, stamp' :: UTCTime
, dname' :: String
, contents' :: String
, ip' :: String
} deriving (Eq, Show, Generic)
and they derive ToJSON / FromJSON / FromRow instances, which is very convenient.
Msg represents the data the API expects when receiving messages and Msg' the data it sends when queried for messages, which has two additional fields that are added by the server, but this doesn't feel right and there has to be a cleaner way to achieve this.
Any insight on an idiomatic way to do deal with this sort of problem appreciated.
I will consider here that you question is more a conceptual one ("What can I do when I have two data types that share some structure ?") than a simple "How do I model inheritance in Haskell ?" that is already replied here.
To answer your question, you will need to consider more than just the structure of your data. For example, if I provide you A and B and if I state that
data A = A Int String
data B = B Int
I doubt that you will automatically make the assumption that a A is a B with an extra String. You will probably try to figure the exact relation between these two data structure. And this is the good thing to do.
If each instance of A can actually be seen as an instance of B then it can be relevant to provide way to represent it in your code. Then you could use a plain Haskell way with a
data A = A { super :: B, theString :: String }
data B = B { id :: Int }
Obviously, this will not be easy to work with these datatype without creating some other functions. For example a fromB function could be relevant
fromB :: B -> String -> A
toB :: A -> B
And you can also use typeclass to access id
class HasId a where
getId :: a -> Int
instance HasId A where
getId = id . super
This is where some help form Lens can be useful. And the answer to this question How do I model inheritance in Haskell? is a good start. Lens package provides Object Oriented syntactic sugar to handle inheritance relationship.
However you can also find that a A is not exactly a B but they both share the same ancestor. And you could prefer to create something like
data A = A { share :: C, theString :: String }
data B = B { share :: C }
data C = C Int
This is the case when you do not want to use a A as a B, but it exists some function that can be used by both. The implementation will be near the previous cases, so I do not explain it.
Finally you could find that there does not really exists relation that can be useful (and, therefore, no function that will really exists that is shared between A and B). Then you would prefer to keep your code.
In your specific case, I think that there is not a direct "is a" relation between Msg and Msg' since one is for the receiving and the other is for the sending. But they could share a common ancestor since both are messages. So they will probably have some constructors in common and accessors (in term of OO programming).
Try to never forget that structure is always bind to some functions. And what category theory teaches us is that you cannot only look at the structures only but you have to consider their functions also to see the relation between each other.

Modeling exchange in Haskell

I'm new to Haskell, and I'm looking to model stock exchange library. It's meant to be a library, hence specifics to be defined by the user. The way I intend to use this is to have users define things like this.
data MyExchange = MyExchange { name :: ExchangeName
, base :: Currency
, quote :: Currency }
deriving (Eq, Show)
instance Exchange MyExchange
data MyExchangeBookMessage =
MyExchangeBookMessage { time :: Time
, exchange :: MyExchange
, price :: Price
, side :: Side
, amount :: Maybe Amount }
deriving (Eq, Show)
instance ExchangeBookMessage MyExchangeBookMessage
I've tried the following, but immediately ran into some limitations of type classes. Below is the code and the error message. Specifically what are the alternatives to parameterizing type classes with multiple types?
Here is the code for the library
module Lib where
data Side = Buy | Sell deriving (Eq, Show)
newtype Amount = Amount Rational deriving (Eq, Show)
newtype Price = Price Rational deriving (Eq, Show)
newtype Currency = Currency String deriving (Eq, Show)
newtype Time = Time Integer deriving (Eq, Show)
type ExchangeName = String
class Exchange a where
name :: a -> ExchangeName
base :: a -> Currency
quote :: a -> Currency
class Message a where
time :: a -> Time
class (Message a, Exchange e) => ExchangeMessage a e where
exchange :: a -> e
class ExchangeMessage a b => BookMessage a b where
price :: a -> Price
side :: a -> Side
amount :: a -> Maybe Amount
And the error message:
src/Lib.hs:22:1: error:
• Too many parameters for class ‘ExchangeMessage’
(Use MultiParamTypeClasses to allow multi-parameter classes)
• In the class declaration for ‘ExchangeMessage’
Later I would like to be able to implement type classes like this:
class Strategy s where
run (Message m, Action a) => s -> m -> a
In the Strategy implementations the run function will take an abstract message m, pattern match it against relevant Message data constructors and return specific action.
I'm porting some Scala code. in Scala I was using a hierarchy of traits with concrete case classes at the bottom:
trait Exchange {
def name: String
def base: Currency
def quote: Currency
}
case class MyExchange(base: Currency, quote: Currency) {
val name = "my-exchange"
}
trait Message {
def time: Long
}
trait ExchangeMessage extends Message {
def exchange: Exchange
}
trait BookMessage extends ExchangeMessage {
def price: Double
def side: Side
def amount: Option[Double]
}
case class MyBookMessage(time: Long, price: Double, side: Side, amount: Option[Double]) {
def exchange: Exchange = MyExchange(...)
}
First order of business, take GHC's suggestion and enable MultiParamTypeCLasses at the top of the file.
{-# LANGUAGE MultiParamTypeClasses #-}
This is a very common extension, and it will fix the immediate problem.
However there appear to be some modeling issues and if you proceed with this design you will surely hit some problems you didn't expect. I can go into all the details of what your code means, but I'm not sure that would be very helpful. Instead I'll just point you in the right direction, I think, which is to use data records instead of typeclasses. Haskell typeclasses do not correspond to classes in other OO langauges and it confuses many beginners. But I think you want to model it like this:
data Exchange = Exchange
{ name :: ExchangeName
, base :: Currency
, quote :: Currency
}
data Message = Message
{ time :: Time }
-- etc.
which will simplify everything for you, and this acts more like OO classes than your model. Keep in mind that records can have functions and other complex data structures as fields, which is how you get the analog of virtual methods, for example:
data MessageLogger = MessageLogger
{ log :: String -> IO () }
First of all, you will probably not be able to write a class instance for ExchangeMessage. The reason is that the exchange function must be able to return any type e. If you want to keep this way, you will need to provide a way to build an arbitrary exchange!
class Exchange a where
name :: a -> ExchangeName
base :: a -> Currency
quote :: a -> Currency
build :: Time -> a
This is the only possible signature for build, as all you can know from an exchange is that it has a Time you can query, and it's probably useless.
What I would think is a better design is to have concrete types for all those classes you defined. For example:
data Exchange = Exchange { getName :: ExchangeName
, getBase :: Currency
, getQuote :: Currency
} deriving (Show, Eq)
Then, once you have written the functions that work with these concrete types, you can either:
write functionsof type MyExchange -> Exchange for example, to adapt functions expecting an Exchange
use classy lenses, so as to directly write functions that will consume abitrary types
All in all, for that kind of applications, if you want to be fancy with types I would suggest to use phantom types for your currencies, so that you'll statically enforce for example you can only compute the sum of two amounts of money using the same currency. Using typeclasses to mimic the habits of OO will not produce APIs that are nice to use or code that is clear.

Defining an HTTP Multipart Post as a Recursive Datatype in Haskell

I cannot wrap my head around how to define a type in Haskell that represents the recursive nature of an HTTP Multipart MIME POST.
In English, a Post is either a list of Headers along with Content of some type, or it's a list of Headers with Content of another Post. But Content can also be a list of Posts.
So I've defined Header thus:
data Header = Header { hName :: String
, hValue :: String
, hAddl :: [(String,String)] } deriving (Eq, Show)
I guess Content should be something like:
data Content a = Content a | [Post] deriving (Eq, Show)
Obviously, that fails: parse error in constructor in data/newtype declaration: [Post]
I've defined Post as:
data Post = Post { pHeaders :: [Header]
, pContent :: [Content] } deriving (Eq, Show)
I'm using Haskell to get a different perspective on my current task, the latest question thereon being here. Just using String for Content, I can parse simple POSTs using Parsec. But the goal is to parse complex Posts.
The link above, and the links found at that question, give the context for my current task. I'm a Haskell hobbyist, so please feel free to offer alternatives to the code I've posted here--I'm not married to it, and I'd love to learn. Ultimately, I'll use F#, unless I am unable to deliver, in which case I'll be forced to use C# and an imperative style. I welcome any wisdom or direction that supports a functional solution!
Your datatypes make sense, your syntax is just wrong:
data Content a = Content a | Posts [Post a] deriving (Eq, Show)
You can name the Posts constructor whatever you like. However, you cannot have something like pContent :: [Content] - since content has a type variable, it must be applied to a type:
data Post a = Post { pHeaders :: [Header]
, pContent :: [Content a] } deriving (Eq, Show)
I would say that your approach is idiomatic Haskell.

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.

When should I use record syntax for data declarations in Haskell?

Record syntax seems extremely convenient compared to having to write your own accessor functions. I've never seen anyone give any guidelines as to when it's best to use record syntax over normal data declaration syntax, so I'll just ask here.
You should use record syntax in two situations:
The type has many fields
The type declaration gives no clue about its intended layout
For instance a Point type can be simply declared as:
data Point = Point Int Int deriving (Show)
It is obvious that the first Int denotes the x coordinate and the second stands for y. But the case with the following type declaration is different (taken from Learn You a Haskell for Great Good):
data Person = Person String String Int Float String String deriving (Show)
The intended type layout is: first name, last name, age, height, phone number, and favorite ice-cream flavor. But this is not evident in the above declaration. Record syntax comes handy here:
data Person = Person { firstName :: String
, lastName :: String
, age :: Int
, height :: Float
, phoneNumber :: String
, flavor :: String
} deriving (Show)
The record syntax made the code more readable, and saved a great deal of typing by automatically defining all the accessor functions for us!
In addition to complex multi-fielded data, newtypes are often defined with record syntax. In either of these cases, there aren't really any downsides to using record syntax, but in the case of sum types, record accessors usually don't make sense. For example:
data Either a b = Left { getLeft :: a } | Right { getRight :: b }
is valid, but the accessor functions are partial – it is an error to write getLeft (Right "banana"). For that reason, such accessors are generally speaking discouraged; something like getLeft :: Either a b -> Maybe a would be more common, and that would have to be defined manually. However, note that accessors can share names:
data Item = Food { description :: String, tastiness :: Integer }
| Wand { description :: String, magic :: Integer }
Now description is total, although tastiness and magic both still aren't.

Resources