从列表中移除x的第一个实例 [英] Removing the first instance of x from a list

查看:236
本文介绍了从列表中移除x的第一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



假设我有以下列表y:



3:3:2:1:9:7:3:[]



我试图找到一种方法来删除列表y中第一个出现的3。这可能使用简单的列表理解吗?



我试过了(这个方法从列表中删除所有实例):

  deleteFirst _ [] = [] 
deleteFirst a(b:bc)| a == b = deleteFirst a bc
|否则= b:deleteFirst a bc


解决方案

列表理解不是解决这个任务的恰当方法(很难一步终止执行)。

你几乎写出了正确的解决方案,只是与匹配值相等,您必须通过返回列表的其余部分而不包含匹配元素来终止计算:

  deleteFirst _ [] = [] 
deleteFirst a(b:bc)| a == b = bc
|否则= b:deleteFirst a bc

> print $ deleteFirst 3(3:3:2:1:9:7:3:[])
> [3,2,1,9,7,3]


I am new to Haskell and have been trying to pick up the basics.

Assume I have the following list y:

3:3:2:1:9:7:3:[]

I am trying to find a way to delete the first occurrence of 3 in list y. Is this possible using simple list comprehension?

What I tried (this method deletes all instances from a list):

deleteFirst _ [] = [] 
deleteFirst a (b:bc) | a == b    = deleteFirst a bc 
                     | otherwise = b : deleteFirst a bc

解决方案

as other already mentioned list comprehension is not an appropriate solution to this task (difficult to terminate the execution at one step).

You've almost written the correct solution, just in the case of equality with the matched value you had to terminate the computation by returning the rest of list without the matched element:

deleteFirst _ [] = [] 
deleteFirst a (b:bc) | a == b    = bc 
                     | otherwise = b : deleteFirst a bc

> print $ deleteFirst 3 (3:3:2:1:9:7:3:[])
> [3,2,1,9,7,3]

这篇关于从列表中移除x的第一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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