0xAX
0xAX

Reputation: 21837

Haskell data type fields

I have my own data type:

type Types = String
data MyType = MyType [Types]

I have a utility function:

initMyType :: [Types] -> MyType
initMyType types = Mytype types

Now I create:

let a = MyType ["1A", "1B", "1C"]

How can I get the list ["1A", "1B", "1C"] from a? And in general, how can I get data from a data constructor?

Upvotes: 3

Views: 1396

Answers (4)

errfrom
errfrom

Reputation: 253

(Answer for future generations.)

So, your task is to obtain all fields from a data type constructor.
Here is a pretty elegant way to do this.

We're going to use DeriveFoldable GHC extension, so to enable it we must change your datatype declaration like so: data MyType a = MyType [a] deriving (Show, Foldable).

Here is a generic way to get all data from a data constructor.
This is the whole solution:

{-# LANGUAGE DeriveFoldable #-}

import Data.Foldable (toList)

type Types = String
data MyType a = MyType [a] deriving (Show, Foldable)

main = 
  let a      = MyType ["1A", "1B", "1C"] :: MyType Types
      result = toList a
  in print result

Printing the result will give you '["1A","1B","1C"]' as you wanted.

Upvotes: 1

nponeccop
nponeccop

Reputation: 13677

There are many ways of pattern matching in Haskell. See http://www.haskell.org/tutorial/patterns.html for details on where patterns can be used (e.g. case statements), and on different kinds of patterns (lazy patterns, 'as' patterns etc)

Upvotes: 2

Max
Max

Reputation: 1680

Besides using pattern matching, as in arrowdodger's answer, you can also use record syntax to define the accessor automatically:

data MyType = MyType { getList :: [Types] }

This defines a type exactly the same as

data MyType = MyType [Types]

but also defines a function

getList :: MyType -> [Types]

and allows (but doesn't require) the syntax MyType { getList = ["a", "b", "c"] } for constructing values of MyType. By the way, initMyTypes is not really necessary unless it does something else besides constructing the value, because it does exactly the same as the constructor MyType (but can't be used in pattern matching).

Upvotes: 8

arrowd
arrowd

Reputation: 34421

You can pattern-match it somewhere in your code, or write deconstructing function:

getList (MyType lst) = lst

Upvotes: 8

Related Questions