How to call an auxiliary function without passing the parameter through the main function

0

I'm trying to solve some basic haskell issues, but I'm having a hard time. I implemented the following code:

type Nome = String
type Preco = Int
type CodigoBarra = Int
type BancoDeDados = [(CodigoBarra, Nome, Preco)]

bd:: BancoDeDados
bd = [(1001,"Refrigerante",450),
     (1002,"Leite",320),
     (1003,"Biscoito",200),
     (1004,"Suco",989),
     (1005,"Arroz",345),
     (1006,"Feijao",780)]

buscarBDaux:: CodigoBarra->BancoDeDados->(Nome,Preco)
buscarBDaux cd ((a,b,c):d) |a == cd = (b,c) 
                           |otherwise = buscarBDaux cd d

Now I need to implement the buscarDB function, which would work like this:

Entry: buscarDB 1006
Output: ("Feijao", 780)

This function would use buscarBDaux , but I'm not able to call buscarBDaux without having passed the database in buscarDB . Could you help me?

    
asked by anonymous 24.02.2018 / 12:38

1 answer

2

As you yourself realized, you should call the bank somehow. The most common solution is to use currying and flip with the buscarDBaux function to create buscarDB , or reorder the buscarDBaux arguments so you do not need to use flip :

-- Usando flip
-- flip :: (a -> b -> c) -> b -> a -> c
buscarDB :: CodigoBarra -> (Nome, Preco)
buscarDB = flip buscarDBaux db

-- Redefinindo buscarDBaux
buscarDBaux :: BancoDeDados -> CodigoBarra -> (Nome, Preco)
buscarDBaux ((a,b,c):d) cd 
    | a == cd   = (b,c) 
    | otherwise = buscarBDaux cd d

buscarDB :: CodigoBarra -> (Nome, Preco)    
buscarDB = buscarDBaux db

The advantage of this method is that you can create several individual functions for each database if you need to. For example, if you have db1 , db2 , and db3 , you can do:

-- Usando buscarDBaux redefinido
buscarDB1 = buscarDBaux db1
buscarDB2 = buscarDBaux db2
buscarDB3 = buscarDBaux db3

Or create a list of search functions using zipWith ($) :

buscas :: [CodigoBarra -> (Nome, Preco)]
buscas = zipWith ($) (repeat buscarDBaux) [db1, db2, db3]

I recommend you read some material on high order functions and currying :

25.02.2018 / 06:46