如何在Haskell中实现搜索

时间:2017-04-08 05:55:55

标签: haskell search addressbook

我一直在关注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"

当前可用的功能只是添加和打印条目。如何为此实现搜索功能?假设我在提示符中输入“name”和“ronaldo”,它只会显示名为ronaldo的条目。

顺便说一句,保存数据(姓名,电话和电子邮件)的代码或容器在哪里可以应用过滤器或elem函数?

感谢。

1 个答案:

答案 0 :(得分:1)

addrs包含要搜索的地址。

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