如何通过在给定的元组中添加元素来在Haskell中构建新的元组
如何将元素添加到元组中?
说,我有一个元组:
info = (13, "Arrabella")
现在,我想创建一个新的元组,以连接给定的元组加一个新元素3.17
,因此开始使用a
当生成的元组应该像以下:
(13, "Arrabella", 3.17)
知道该怎么做?我用++
运算符我用list
进行此操作似乎没有用于元组...
How can I add an element to a tuple?
Say, I have a tuple:
info = (13, "Arrabella")
Now I want to create a new tuple conatining the given tuple plus a new element 3.17
, so when starting with a
the resulting tuple should be like following:
(13, "Arrabella", 3.17)
Any idea how to do this? The ++
operator I'd use to do this with a List
doesn't seem to be implemented for tuples...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将现有值映射到新的3翼元组中,因此:
的确,
(++):: [a] - > [a] - > [a]
获取两个列表,并返回一个列表,该列表是两个给定列表的串联。这也意味着列表中的项目都具有相同的类型,并且两个列表中的项目具有相同的类型。
一个人可以制作一个任意长度的打字机来连接元素,
但这也不会有帮助,因为您在这里在元组中添加一个元素,而不是连接两个元素。您可以创建一个额外的类型来附加一个项目:
因此,您可以使用
(13,“ arrabella”)++> 3.17
创建一个3元组。You can map the existing values to a new 3-tuple, so:
Indeed,
(++) :: [a] -> [a] -> [a]
takes two lists and returns a list that is the concatenation of the two given lists. This also means that the items in the list all have the same type, and that the items in the two lists have the same type.One could make a typeclass to concatenate tuples with an arbitrary length, for example with:
But this will not help here either since you here add one element to the tuple, not concatenate two tuples. You can create an extra typeclass to append a single item:
Then you thus can use
(13, "Arrabella") ++> 3.17
to create a 3-tuple.您需要使用模式来解构元组,然后构建新的元组。
在
ghci
中,您必须在模式的前面使用Let
:在源文件中,您可以直接输入它,而无需
Let
:加载源文件在带有
的解释器中:l sourcename.hs
和:You need to use a pattern to deconstruct the tuple, and then construct the new tuple.
In
ghci
you must uselet
in front of the pattern:In a source file you type it in directly, without
let
:Load your source file in the interpreter with
:l sourceName.hs
, and: