学习Haskell:如何从Haskell的列表中删除一个项目 [英] Learning Haskell: How to remove an item from a List in Haskell

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

问题描述

试图学习Haskell。我试图写一个简单的函数来从列表中删除一个数字而不使用内置函数(删除...我想)。为了简单起见,我们假设输入参数是一个整数,列表是一个整数列表。这里是我的代码,请告诉我下面的代码有什么问题

  areTheySame :: Int  - >内部 - > [Int] 

areTheySame x y | x == y = []
|否则= [y]

removeItem :: Int - > [Int] - > [Int]

removeItem x(y:ys)= areTheySame xy:removeItem x ys


解决方案

其他人是正确的,问题是操作符。尽管如此,我会说你的 areTheSame 函数返回一个列表是错误的。

  removeItem _ [] = [] 
removeItem x(y:ys)| x == y = removeItem x ys
|否则= y:removeItem x ys

正如您所看到的,这是一个相当简单的实现。而且,对于你的程序来说,这样的收费要比将大量列表附加在一起要少得多。它还有其他好处,例如懒洋洋地工作。

Trying to learn Haskell. I am trying to write a simple function to remove a number from a list without using built-in function (delete...I think). For the sake of simplicity, let's assume that the input parameter is an Integer and the list is an Integer list. Here is the code I have, Please tell me what's wrong with the following code

areTheySame :: Int -> Int-> [Int]

areTheySame x y | x == y = []
                | otherwise = [y]

removeItem :: Int -> [Int] -> [Int]

removeItem x (y:ys) = areTheySame x y : removeItem x ys

解决方案

The others are right that the problem is the : operator. I would say that your areTheySame function that returns a list is the wrong approach anyway, though. Rather than switch to the ++ operator, a better implementation of that function would be:

removeItem _ []                 = []
removeItem x (y:ys) | x == y    = removeItem x ys
                    | otherwise = y : removeItem x ys

As you can see, this is a pretty simple implementation. Also, consing like this is much less taxing for your program than appending a bunch of lists together. It has other benefits as well, such as working lazily.

这篇关于学习Haskell:如何从Haskell的列表中删除一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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