简体   繁体   中英

How to implement searching in Haskell

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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