3

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?

0

4 Answers 4

8

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).

Sign up to request clarification or add additional context in comments.

Comments

8

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

getList (MyType lst) = lst

Comments

2

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)

Comments

1

(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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.