我真的很困惑你应该如何从 haskell 中的类型类中获取数据。我是有 C 背景的,所以发现很难只访问数据。我所拥有的是这样的:
data MyType = MyType String deriving (Show)
display :: [MyType] -> IO ()
display ((MyType name):xs) = do
display xs
putStr name
基本上在这里我想访问“名称”,但它似乎不起作用。我可以通过在代码中引用对象来访问类型类实例中的数据,还是必须将其内容映射到变量?如果是这样怎么办?
关于这方面的优秀教程的链接将不胜感激,我读过“为你学习 Haskell 以获得巨大的好处”,但是当我尝试偏离给出的示例时,我似乎总是需要知道太多才能完成它。
-一个
I'm really confused about how your supposed to get data out of typeclasses in haskell. I'm coming for a C background so finding it really difficult that you can't just access the data. What I have is something like this:
data MyType = MyType String deriving (Show)
display :: [MyType] -> IO ()
display ((MyType name):xs) = do
display xs
putStr name
Basically here I want to access 'name' however it just doesn't seem to work. Can I access the data within an instance of a typeclass by just having a reference to the object in my code or do I have to map its contents to variables? and if so how?
Links to good tutorials on this would be appreciated, I've read 'Learn you a Haskell for great good' but when I try to deviate from the examples given there always seems to be to much I need to know to get it done.
-A
发布评论
评论(2)
我想你可能只是错过了一些将它们联系在一起的小片段。
首先,您有一个完美的数据类型,
MyType
,它保存字符串:现在,您想要编写一个函数来遍历这种类型的列表,并打印每个元素。我们通过列表数据类型的递归来完成此操作。
由于列表有两种情况,即空列表
[]
和 cons 情况(:)
,因此我们有两个分支:现在,我认为您可能会去哪里卡住了正在构建一些这种类型的数据。您已经知道如何通过模式匹配将其分解,并且使用几乎相同的语法构建数据。下面是
MyType
的列表:最后,您可以从
main
运行您的程序注意,这里没有类型类,只有代数数据类型(通过数据)。
I think you might just be missing some little pieces that tie it all together.
Firstly, you have a perfectly fine data type,
MyType
, that holds strings:Now, you want to write a function that walks a list of such type, printing each element as it goes. We do this via recursion over the list data type.
Since lists have two cases, the empty list,
[]
, and the cons case,(:)
, we have two branches:Now, where I think you might have go stuck was building some data of this type. You already know how to take it apart with pattern matching, and you build the data using almost the same syntax. Here's a list of
MyType
:Finally, you can run your program from
main
Note, there's no typeclasses here, just algebraic data types (introduced with
data
).首先,我对你使用的词语有点困惑。 类型类是一种重载函数的方法。您拥有的是代数数据类型。你遇到的问题(如果我理解正确的话)是众所周知的。为了更轻松地访问数据,您可以使用记录语法:
您是否看到与 C 中的结构体相似?使用记录语法,一些有趣的事情是可能的:
还有其他一些事情。
First of all, I am a bit confused about the words you use. A typeclass is a way to overload functions. What you have is an algebraic data type. The problem you have (if I understood it correctly) is well known. For the purpose of accessing data easier, you could use record syntax:
Do you see the similarity to a struct in C? Using record syntax, some interesting things are possible:
and some other thing too.