Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building lists of data types in Haskell

I'm really confused about how your supposed to get data out of typeclasses in haskell. I'm coming for a C background so finding it really difficult that you can't just access the data. What I have is something like this:

data MyType = MyType String deriving (Show)


display :: [MyType] -> IO ()
display ((MyType name):xs) = do
       display xs
       putStr name

Basically here I want to access 'name' however it just doesn't seem to work. Can I access the data within an instance of a typeclass by just having a reference to the object in my code or do I have to map its contents to variables? and if so how?

Links to good tutorials on this would be appreciated, I've read 'Learn you a Haskell for great good' but when I try to deviate from the examples given there always seems to be to much I need to know to get it done. -A

like image 293
Andy Avatar asked May 04 '11 19:05

Andy


2 Answers

I think you might just be missing some little pieces that tie it all together.

Firstly, you have a perfectly fine data type, MyType, that holds strings:

data MyType = MyType String deriving (Show)

Now, you want to write a function that walks a list of such type, printing each element as it goes. We do this via recursion over the list data type.

Since lists have two cases, the empty list, [], and the cons case, (:), we have two branches:

display :: [MyType] -> IO ()
display []                 = return ()
display ((MyType name):xs) = do
       putStrLn name
       display xs

Now, where I think you might have go stuck was building some data of this type. You already know how to take it apart with pattern matching, and you build the data using almost the same syntax. Here's a list of MyType:

table = 
    [ MyType "john"
    , MyType "don"
    , MyType "eric"
    , MyType "trevor"
    ]

Finally, you can run your program from main

main = display table

Note, there's no typeclasses here, just algebraic data types (introduced with data).

like image 104
Don Stewart Avatar answered Sep 22 '22 19:09

Don Stewart


First of all, I am a bit confused about the words you use. A typeclass is a way to overload functions. What you have is an algebraic data type. The problem you have (if I understood it correctly) is well known. For the purpose of accessing data easier, you could use record syntax:

data Foo = Foo {
    bar :: Int
  , baz :: String
}

Do you see the similarity to a struct in C? Using record syntax, some interesting things are possible:

bar y -- access member bar of y
y { bar = z } -- Make a new record but with field bar changed to the value of z

and some other thing too.

like image 28
fuz Avatar answered Sep 20 '22 19:09

fuz