简体   繁体   中英

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?

您可以在代码中的某个位置进行模式匹配,或者编写解构函数:

getList (MyType lst) = lst

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

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 (eg case statements), and on different kinds of patterns (lazy patterns, 'as' patterns etc)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM