Creating Data Type Lists in Haskell

I am really confused about how you should get data from classes in haskell. I come to C-background, so it’s very difficult to understand that you cannot just access the data. I have something like this:

data MyType = MyType String deriving (Show)


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

Mostly here I want to access the "name", however it just doesn't work. Can I access data in an instance of typeclass just by having a reference to an object in my code, or do I need to map its contents to variables? And if so, how?

Links to good lessons on this subject will be appreciated, I read: “Teach you Haskell for excellent,” but when I try to deviate from the examples given, it always seems to me that I need to know to get it done. -A

+5
source share
2 answers

I think you could just skip some small pieces that tie it all together.

Firstly, you have a perfectly fine data type MyType, which contains strings:

data MyType = MyType String deriving (Show)

Now you want to write a function that scans a list of this type, printing each element as it appears. We do this through recursion on the list type.

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

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

, , , , , . , , , . MyType:

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

, main

main = display table

: , ( data).

+6

, , . typeclass - . . , ( ), . :

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

C? , :

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

.

+1

All Articles