Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 如何获取自定义数据类型成员?_Haskell - Fatal编程技术网

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

Haskell 如何获取自定义数据类型成员?,haskell,Haskell,这就是我迄今为止所尝试的。我想用一个字符串和两个Ints创建一个类型Info。现在我想访问该类型的给定实例的字符串。我读过 我没想到这会起作用,但无法搜索我正在寻找的内容: Prelude> data Info = Info String Int Int Prelude> aylmao = Info "aylmao" 2 3 Prelude> aylmao . String <interactive>:4:1: error: • Couldn't mat

这就是我迄今为止所尝试的。我想用一个
字符串和两个
Int
s创建一个类型
Info
。现在我想访问该类型的给定实例的
字符串。我读过

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

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> 
Prelude>data Info=Info String Int
前奏曲>艾尔玛=信息“艾尔玛”2 3
前奏曲>艾尔玛。一串
:4:1:错误:
•无法将预期类型“b0->c”与实际类型“Info”匹配
•在“(.”的第一个参数中,即“aylmao”
在表达式中:aylmao。一串
在“it”的方程式中:it=aylmao。一串
•相关绑定包括
it::a->c(绑定时间:4:1)
:4:10:错误:
数据构造函数不在范围内:String::a->b0
序曲>
我希望能够访问我类型的任何匿名成员,我如何才能做到这一点

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

data Info = Info String Int Int
正如Willem Van Onsem所说,您可以编写一个函数来实现以下功能:

infoString :: Info -> String
infoString (Info s _ _) = s
或者,您可以命名数据类型字段:

data Info = Info { infoString :: String
                 , infoInt1   :: Int
                 , infoInt2   :: Int
                 }
并将自动生成的
infoString::Info->String
用作函数


最好为这些字段提供更好的名称。

使用模式匹配:
getInfoString(Info x\uuux)=x
然后可以使用
getInfoString aylmoa
调用它。请注意,在Haskell中,
不用于访问属性。这是函数组合运算符。@WillemVanOnsem非常感谢您的快速回答,将其作为搜索引擎优化等的答案。我将在稍后接受bit@zython:此部分的答案为。可能的副本为