Haskell中是否存在“对象平等”的感觉? [英] Is there a sense of 'object equality' in Haskell?

查看:92
本文介绍了Haskell中是否存在“对象平等”的感觉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 数据LL a =空| Node a(LL a)派生(Show,Eq)

我可以很容易地实现插入结束和开始。但是在特定元素之后或之前插入什么呢?如果我有一个 LL Integer ,我可以在插入 4之间区别Haskell 在包含 1 的特定节点之后,而不是第一个 1 处理列表?

 节点1(节点2(节点3(节点1空)))

我很好奇 insertAfter 方法是如何看起来可以的指定在包含1的特定节点之后插入5。如果我想在包含 1 的第一个节点之后插入,我是否必须传入整个列表来指定该节点,而对于最后一个节点,只需节点1空



我不确定是否正确地将此视为对象相等 - 但我想知道是否有一种方法可以在这样的数据结构中引用具有相同有效载荷的类型的特定元素。

解决方案

不,那里是不是这样的事情。分辨价值的唯一方法是通过它们的结构;在某些语言中没有像 identity 那样的对象。也就是说,你无法区分这两个值:(Just 5,Just 5)的行为与 let x = Just 5完全相同在(x,x)中。同样,this Node 1 和其他一些 Node 1 之间没有区别:它们是无法区分的。

通常这个问题的解决方案是以其他方式思考你的问题,以便不再需要根据身份进行区分(并且通常在事实是没有必要的)。但是,正如评论中所提到的那样,您可以自己模拟其他语言的指针机制,方法是生成某种类型的不同标记(例如,增加整数),并为每个对象分配一个,以便可以区分它们。


If I have a singly linked list in Haskell:

data LL a = Empty | Node a (LL a) deriving (Show, Eq)

I can easily implement methods to insert at the end and at the beginning. But what about inserting after or before a particular element? If I have a LL of Integer, can I make a distinction in Haskell between inserting 4 after a particular node containing a 1, rather than the first 1 that it sees when processing the list?

Node 1 (Node 2 (Node 3 (Node 1 Empty)))

I'm curious how an insertAfter method would look that you would be able to specify "insert 5 after this particular node containing a 1". If I wanted to insert after the first node containing 1, would I have to pass in the entire list to specify this, and for the last node, only Node 1 Empty?

I'm not sure if it's right to address this as 'object equality'- but I'm wondering if there's a way to refer to particular elements of a type with the same payload in a data structure like this.

解决方案

No, there is no such thing. The only way to tell apart values is by their structure; there is no identity like objects in some languages have. That is, there's no way you could tell apart these two values: (Just 5, Just 5) behaves exactly the same as let x = Just 5 in (x, x). Likewise, there is no difference between "this Node 1" and "some other Node 1": they are indistinguishable.

Usually the "solution" to this problem is to think of your problem in some other way so that there's no longer a need to distinguish based on identity (and usually there in fact is no need). But, as mentioned in the comments, you can emulate the "pointer" mechanic of other languages yourself, by generating distinct tags of some sort, eg increasing integers, and assigning one to each object so that you can tell them apart.

这篇关于Haskell中是否存在“对象平等”的感觉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆