Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I make a list of types in haskell?

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]
like image 237
Marcus Ruddick Avatar asked Feb 21 '17 23:02

Marcus Ruddick


People also ask

Can lists in Haskell have different types?

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?

How do I print a list of elements in Haskell?

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.

Does Haskell have lists?

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.


1 Answers

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).

like image 167
Reid Barton Avatar answered Nov 05 '22 02:11

Reid Barton