Home > OS >  Print List out of a datatype
Print List out of a datatype

Time:12-11

I'm working on a datatype that involves the name and surname of a person, their direction and the city they live in. I made a function to print this, but I'm pretty sure I can instance somehow Show or make another class and instance it. I have this data type called Direction:

type Direction = (Person, Dir, City) 
type Name = String
type Surname = String
type City = String
data Person = Per Name Surname
data Dir = Street String Int | House String 

And this two elements:

dirJon:: Direction
dirJon = (Per "Jon" "Prieto", House "Enea", "Orio")
dirMiren:: Direction
dirMiren = (Per "Miren" "Artola", Street "Aldamar" 15, "Donostia")

So the function I came up with is:

write:: [Direction] -> IO() 
write [] = return ()
write ((Per a b,Street c d, e):cs) = do
                                     putStrLn ( a    ' ': b)
                                     putStrLn ("c/"    c   'c':show d)
                                     putStrLn e
                                     write cs
write ((Per a b,House c, e):cs) = do
                                     putStrLn ( a    ' ': b)
                                     putStrLn ("House "    c)
                                     putStrLn e
                                     write cs

Which leads into a correct implementation, meaning that if I call write [dirJon,dirMiren] prints correctly :

Jon Prieto
casa Enea
Orio
Miren Artola
c/Aldamarc15
Donostia

(In different lines, I don't wanna make a paper out of this).

So if anyone could help me out make a instance of it somehow, because I already tried making a class that uses [Direction] as a parameter but since its a type and not a data I can't do it.

CodePudding user response:

You can't define instances for type aliases. I would just define a proper data type.

type Name = String
type Surname = String
type City = String
data Person = Per Name Surname
data Location = Street String Int | House String 
data Address = Address Person Location City

addrJon, addrMiren :: Address
dirJon = Address (Per "Jon" "Prieto") (House "Enea") "Orio"
dirMiren = Address (Per "Miren" "Artola") (Street "Aldamar" 15) "Donostia"

instance Show Person where
    show (Per x y) = x    " "    y

instance Show Location where
    show (Street name number) = "c/"    name    "c"    show number
    show (House name) = "House "    name

instance Show Address where
    show (Address p l c) = show p    "\n"    show l    "\n"    c

write :: [Address] -> IO() 
write [] = return ()
write (a:as) = putStrLn (show a) >> write as
-- write = traverse print
  • Related