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

Asked

Viewed 276 times

0

I’m trying to solve some basic Haskell problems, 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 function buscarDB,that would work like this:

Entree: buscarDB 1006
Exit: ("Feijao", 780)

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

1 answer

2


As you yourself noticed, you should call the bank somehow. The most common solution make use of currying and flip with the function buscarDBaux to raise buscarDB, or reorder the arguments of buscarDBaux so you don’t have 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, it is possible to 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:

  • Thanks for the help luispauloml, solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.