如何获得自定义数据类型成员?

时间:2018-04-25 08:19:53

标签: haskell

这是我到目前为止所尝试的。我想创建一个Info类型String和两个Int。现在我想访问该类型的给定实例的String。我看过Accessing members of a custom data type in Haskell

我没想到这会起作用,但无法搜索我正在寻找的东西:

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> 

我希望能够访问我类型的任何匿名成员,我该怎么做?

1 个答案:

答案 0 :(得分:6)

  

如何获取自定义数据类型成员?

data Info = Info String Int Int

正如Willem Van Onsem所说,你可以写一个这样做的功能:

getInfoString :: Info -> String
getInfoString (Info x _ _) = x

或者您可以use record syntax命名您的数据类型字段:

data Info = Info { infoString :: String
                 , infoInt1   :: Int
                 , infoInt2   :: Int
                 }

并使用infoString :: Info -> String作为函数。

最好为这些领域提出更好的名称。