在Haskell中添加列表/覆盖现有列表的功能 [英] Functionality of adding to lists in Haskell / overwriting an existing List

查看:89
本文介绍了在Haskell中添加列表/覆盖现有列表的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type Dictionary = [(String, String)]

dict :: Dictionary
dict = ("Deutsch", "English"):[]

insert :: Dictionary -> (String,String) -> Dictionary
insert dict entry = dict ++ [entry]

关于列表工作方式我找不到的一件事:是否可以用insert中添加的条目覆盖现有字典?还是有必要在下一步中始终写出通过插入插入的列表?

One thing that I didn't find about the way lists work: Is it somehow possible to overwrite the existing dict with the entry added in insert? Or is it necessary to, in the next step, always write out the list that was put out by insert?

insert [("German", "English"), ("Hallo", "hello")] ("Versuch", "try")

到目前为止,这是我能够在不丢失先前条目的情况下向新列表添加内容的唯一方法.但是,接下来要执行的事情是搜索命令,所以我想知道是否也必须在搜索功能中将其写出来.

So far, this is the only way I have been able to add something to the new list without losing the previous entry. However, next on the list of things to implement is a search command, so I wonder if I'd also have to write this out in the search function.

推荐答案

函数式编程的想法通常是您的数据是不可变的.这意味着一旦创建了列表,就永远无法更改该列表.但是您可以复制该列表,对其进行修改,并保留该列表.

The idea of functional programming is in general that your data is immutable. This means once you have created a list, you can NEVER change that list. But you can copy that list, make modifications to it, and keep that as well.

所以当您有这样的列表

test = [1,2,3]

我们可以通过在开头添加4来修改它:

We can modify this by adding 4 to the start:

test2 = 4 : test

:称为cons运算符,将元素放在列表前面.请注意,x:xs(与执行[x]++xs相同)比执行xs++[x]

: called the cons operator, puts an element in front of a list. Do note that x:xs (the same as doing [x]++xs) has a better performance than doing xs++[x]

所以现在我们有两个绑定,test[1,2,3]之一,test2[4,1,2,3]

So now we have two bindings, one of test to [1,2,3] and one of test2 to [4,1,2,3]

希望这可以使事情变得清晰

Hope this clarifies things

举一个完整的例子:

type Dictionary = [(String, String)]

insert :: Dictionary -> (String,String) -> Dictionary
insert dict entry = dict ++ [entry]

dict0 = [ ("Deutsch", "English") ]
dict1 = insert dict0 ("Hallo", "hello")
dict2 = insert dict1 ("Versuch", "try")


如果您是函数式编程的新手,我建议您阅读了解Haskell带来的好处,一本很棒的(免费的)关于如何使用Haskell的书-以及一般的函数式编程.


If you're new to functional programming, I would recommend reading Learn You a Haskell for Great Good , which is a fantastic (and free) book on how to use Haskell -- and functional programming in general.

这篇关于在Haskell中添加列表/覆盖现有列表的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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