Haskell递归查找函数

时间:2015-11-24 11:34:16

标签: haskell recursion

我的代码包含超市的库存清单:

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,我在其中输入条形码并获取产品的名称和价格。它应该是一个递归函数,在列表中搜索匹配的条形码。但是我该怎么做呢?

感谢您的帮助

3 个答案:

答案 0 :(得分:2)

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

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

在查找条形码bc时,您的案例中的谓词可以是

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

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

您可能需要为记录样式参数命名,命名类型以使其与单个广告资源项匹配,并使用类型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

并且,正如Cactus建议的那样,使用Data.List.lookup作为您的函数findArticle

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