2

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?

hnefatl
  • 5,860
  • 2
  • 27
  • 49
zython
  • 1,176
  • 4
  • 22
  • 50
  • 3
    with pattern matching: `getInfoString (Info x _ _) = x` – Willem Van Onsem Apr 25 '18 at 08:21
  • 1
    then you can call it with `getInfoString aylmoa`. Note that in Haskell, the `.` is not used to access attributes. It is the function composition operator. – Willem Van Onsem Apr 25 '18 at 08:24
  • @WillemVanOnsem awesome thanks for the quick answer, put it as an answer for SEO etc. I'll accept in a bit – zython Apr 25 '18 at 08:25
  • 1
    @zython: This part is answered in [LYAH chapter 8.2: Making Our Own Types and Typeclasses, Record Syntax](http://learnyouahaskell.com/making-our-own-types-and-typeclasses#record-syntax). – sshine Apr 25 '18 at 08:45
  • Possible duplicate of [Haskell pattern matching - what is it?](https://stackoverflow.com/questions/2225774/haskell-pattern-matching-what-is-it) – jberryman Apr 25 '18 at 19:38

1 Answers1

6

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.

Community
  • 1
  • 1
sshine
  • 15,635
  • 1
  • 41
  • 66