繁体   English   中英

Haskell递归查找功能

[英]Haskell recursive find Function

我的超市库存清单中有以下代码:

type Barcode = Int
type Name = String
type Price = Int
data Inventory = Inventory Barcode Name Price deriving (Eq, Ord, Show)

marktInventar :: [(Int,String,Int)]
marktInventar = [ (321, "Salz",     35)
                , (432, "Butter",   95)
                , (531, "Milch",    85)
                , (235, "Eier",    145)
                , (246, "Schmalz", 245)
                , (642, "Mehl",    110)
                , (528, "Safran",  249)
                , (395, "Wurst",   345)
                , (294, "Kaese",   215)
                , (178, "Tomate",   45)
                , (378, "Banane",   75)
                , (938, "Orange",   65)
                , (491, "Kiwi",     95)
                ]

仅列出了我,其余的由我自己完成,我希望它是正确的。 现在,我应该构建一个函数findArticle,在其中输入条形码并获取产品的名称和价格。 它应该是一个递归函数,在列表中搜索匹配的条形码。 但是我该怎么做呢?

感谢帮助

您不需要自己编写递归函数Data.List已经使用以下签名导出了find函数:

find :: Foldable t => (a -> Bool) -> t a -> Maybe a

给定要查找的条形码bc ,您的情况中的谓词可以是

\(bc', _, _) -> bc' == bc

如果找到条形码Just (_, name, price)结果将为Just (_, name, price) ,否则为Nothing

这是一个递归版本,但是请记住,这不是最佳选择:

findIt :: Barcode -> [Inventory] -> (Name, Price)
findIt code [] = ()
findIt code ((Inventory bc n p):xs) | code == bc = (n, p)
                                    | otherwise  = findIt code xs

您可能想要命名记录样式参数,命名类型以使其与单个库存项目匹配,并使用Inventory类型来反映整个库存(例如,项目列表):

type Barcode = Int
type Name = String
type Price = Int
data InventoryItem = InventoryItem { barcode :: Barcode
                                   , name    :: Name
                                   , price   :: Price
                                   }
                     deriving (Eq, Ord, Show)
type Inventory = [(Barcode, InventoryItem)]

然后,您可以将marktInventar转换为Inventory

inventory :: Inventory
inventory = map (\(bc, n, p) -> (bc, InventoryItem bc n p)) marktInventar

并按照仙人掌的建议,将Data.List.lookup用于函数findArticle

findArticle :: Barcode -> Inventory -> Maybe InventoryItem
findArticle = lookup

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM