0

I've been following a sample addressbook program in Haskell:

menu = "1.Add address\n2.List addresses\n3.Exit"
main = do
    prompt []

data Address=Address String String String    
    deriving Show

prompt :: [Address] -> IO()
prompt addrs=  do 
    putStrLn menu
    choice <- getLine
    interpret addrs choice

interpret :: [Address]->String -> IO()
interpret addrs "1" = do
    putStr "Names:"
    names <- getLine

    putStr "Phone:"
    phone <- getLine

    putStr "Email:"
    email <- getLine


    putStrLn "Address added"
    prompt (addAddr(getAddr names phone email) addrs)

interpret addrs "2" = do 
    printAddrs addrs
    prompt addrs


interpret addrs "3" = putStrLn "Good bye"
interpret _ _ = putStrLn "Don't know what to do with ya!"

getAddr ::String->String->String->Address
getAddr names phone email = Address names phone email

addAddr::Address->[Address]->[Address]
addAddr addr addrs = addr:addrs

printAddrs::[Address]->IO()
printAddrs addrs= putStrLn (fmtAddresses (tail addrs) (head addrs) "")

fmtAddresses::[Address]->Address->String->String
fmtAddresses addrs (Address names phone email) str
    | (length addrs==0) = currStr
    | (length addrs /=0 ) = fmtAddresses (tail addrs) (head addrs) currStr 
    where currStr = str++"Names:"++names++"Phone:"++phone++"Email:"++email++"\n"

The current available functions are just add and print entries. How can I implement a search function for this? Let's say if I put "name" and "ronaldo" in the prompt, it will just display entries with name ronaldo.

By the way, where is the code or container that holds the data (names, phone and email) where I can apply filter or elem function?

Thanks.

pgtr3s
  • 19
  • 3

1 Answers1

1

addrs holds the addresses to search through.

interpret addrs "4" = do
  putStr "Fulltext search keyword:"
  word <- getLine
  printAddrs (filter (\(Address name phone email)
      -> isInfixOf word name
      || isInfixOf word phone
      || isInfixOf word email
    ) addrs)
  prompt addrs
Gurkenglas
  • 2,317
  • 9
  • 17
  • Thanks. Btw, Im getting the error addressbook.hs:36:12: error: Variable not in scope: isInfixOf :: () -> String -> Bool – pgtr3s Apr 08 '17 at 07:38
  • Got it. Needed to import Data.List and word <- getLine is the one that works for me – pgtr3s Apr 08 '17 at 09:34