I have different data types that I have defined, and I want to make them all an instance of a class. is it possible to make a list of types and map instance over them instead of having to declare them all individually?
I mean something like this:
data Type1 = ...
data Type2 = ...
map (instance ClassName) [Type1, Type2]
One is of type (String,Int) , whereas the other is (Int,String) . This has implications for building up lists of tuples. We could very well have lists like [("a",1),("b",9),("c",9)] , but Haskell cannot have a list like [("a",1),(2,"b"),(9,"c")] . Which of these are valid Haskell, and why?
If show is ok to print your elements, you can use putStr ( unlines $ map show [(1,"A"),(2,"B"),(3,"C"),(4,"D")]) but you can replace show by any funtion that'll take your custom type and return a string.
In Haskell, lists are a homogenous data structure. It stores several elements of the same type. That means that we can have a list of integers or a list of characters but we can't have a list that has a few integers and then a few characters.
Well actually you can, with something like
{-# LANGUAGE TemplateHaskell #-}
module T where
class C a
data X = X
data Y = Y
data Z = Z
$(fmap concat $ mapM (\t -> [d|instance C $t|]) [[t|X|], [t|Y|], [t|Z|]])
but it strikes me as massive overkill unless you actually need them to be generated automatically (e.g., the list of types might vary depending on something).
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