質問

I want to write a Haskell function that takes a custom type with eleven fields and returns either a list of all the fields' values, or a map associating the fields' names with their values. I don't want to have to explicitly get every field because that would be verbose and less versatile. Is there any way to do this?

役に立ちましたか?

解決

What you write would be possible to some degree, but it wouldn't be very useful.

Let's imagine we insist on writing this function for a moment. Given that the fields' values may have different types, you probably rather want to yield a tuple. I.e.

data MyType = MyType Int String Bool

getFields :: MyType -> (Int, String, Bool)
getFields (MyType a b c) = (a,b,c)

So you could now call it like

let v = MyType 1 "Hello" True
let (x, y, z) = getFields v

Now, this isn't actually very useful, because you could use pattern matching in all of these cases, e.g.

let v = MyType 1 "Hello" True
let (MyType x y z) = v

Alright, but what if you wanted to address individual fields? Like

let x = fst (getFields v)

...how to do that without a 'getFields' function? Well, you can simply assign field names (as you probably already did):

data MyType = MyType
          { i :: Int
          , s :: String
          , b :: Bool
          }

Now you could functions for accessing indivial fields for free:

let x = i v

...since assigning names ot fields actually generates functions like i :: MyType -> Int or s :: MyType -> String.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top