从 haskell 中创建的数据类型列表中筛选元素



我是Haskell的新手,我试图从一个名为Hoover的创建数据类型中过滤元素。

现在胡佛有价格和瓦数 ,我把胡佛定义为:

data Hoover = HH Price Wattage

& 价格和瓦数为:

data Price = P Int 
data Wattage = W Int 

当我尝试运行此代码以从不同价格的胡佛目录中过滤胡佛时:

(这里 m 是最低价格,n 是最高价格(:

filterProduct :: Price -> Price -> [Hoover] -> [Hoover]
filterProduct (P m) (P n) [] = []
filterProduct (P m) (P n) (x:xs) = if(price >= m && price <= n) then ([x] ++ (filterProduct (P m) (P n) xs))
else (filterProduct (P m) (P n) xs)
where
x :: Hoover 
x = HH (P price) watt

我收到很多错误,我尝试做很多事情,但无法解决它,需要帮助修复它

将不胜感激任何帮助!

在你的程序中,price似乎是凭空出现的。您不会在表达式的头部(在=之前(定义它。所以编译器不明白你在做什么。

您实际上以错误的方式编写了wherecaluse。该模式位于等式的左侧,因此:

filterProduct :: Price -> Price -> [Hoover] -> [Hoover]
filterProduct (P m) (P n) [] = []
filterProduct (P m) (P n) (x:xs) = if(price >= m && price <= n) then ([x] ++ (filterProduct (P m) (P n) xs))
else (filterProduct (P m) (P n) xs)
whereHH (P price) watt = x

话虽如此,你把事情搞得太难了。您可以使用此处的filter :: (a -> Bool) -> [a] -> [a]函数来过滤列表:

filterProduct :: Price -> Price -> [Hoover] -> [Hoover]
filterProduct (P m) (P n) = filter ((HH (P price) watt) -> price >= m && price <= n)

此外,定义类型同义词可能更有意义:

type Price = Int
type Wattage = Int

如果不打算在这些类型上定义特殊类型类实例。

Willem Van Onsem的回答一如既往地出色,似乎已经解决了您的问题。我仍然想提出另一种方法,使用记录语法:

data Hoover = HH
{ hooverPrice   :: Int
, hooverWattage :: Int
}

如果你像这样声明你的类型,它会给你两个函数hooverPricehooverWattage类型Hoover -> Int

现在,如果您有一个可以检查Int是否在您想要的价格范围内的函数,您只需将该函数与hooverPrice组成,您将拥有一个函数来检查真空吸尘器的价格是否在该范围内。有了这个功能,问题就变成了一个简单的filter

最新更新