zython
zython

Reputation: 1288

How to get custom data type member?

This is what I have tried so far. I wanted to make a type Info with a String and two Ints. Now I want to access the String for a given instance of that type. I have read Accessing members of a custom data type in Haskell.

I did not expect this to work but couldn't search for what I'm looking for:

Prelude> data Info = Info String Int Int
Prelude> aylmao = Info "aylmao" 2 3
Prelude> aylmao . String 

<interactive>:4:1: error:
    • Couldn't match expected type ‘b0 -> c’ with actual type ‘Info’
    • In the first argument of ‘(.)’, namely ‘aylmao’
      In the expression: aylmao . String
      In an equation for ‘it’: it = aylmao . String
    • Relevant bindings include
        it :: a -> c (bound at <interactive>:4:1)

<interactive>:4:10: error:
    Data constructor not in scope: String :: a -> b0
Prelude> 

I want to be able to access any anonymous member of my type, how can I do this?

Upvotes: 2

Views: 2288

Answers (1)

sshine
sshine

Reputation: 16145

How to get custom data type member?

data Info = Info String Int Int

As Willem Van Onsem said, you can write a function that does this:

infoString :: Info -> String
infoString (Info s _ _) = s

Or you can use record syntax to name your data type fields:

data Info = Info { infoString :: String
                 , infoInt1   :: Int
                 , infoInt2   :: Int
                 }

and use the automatically generated infoString :: Info -> String as a function.

Preferrably, come up with better names for those fields.

Upvotes: 6

Related Questions