Haskell Phonebook adding elements

2019-09-24 08:05发布

He guys,

My task is to program a phonebook in Haskell. Therefore type Phonebook is given. The Phonebook maps names(String) to their phone numbers(String). But now I have problems implementing the function 'insert':

Heres the code:

type Phonebook = String -> String

emptyPhonebook :: Phonebook
emptyPhonebook  = \_->""

insert :: String -> String -> Phonebook -> Phonebook
insert name number emptyPhonebook = (\name->number)     --is this correct?
insert name number existingPhonebook = ??

My question: How do I insert a function in a function? I mean now I have to insert an entry consisting of a function (name -> number) in another function (existing Phonebook) or am I wrong? Thanks for helping me out :)

1条回答
▲ chillily
2楼-- · 2019-09-24 08:28

Something like this should work:

type Phonebook = String -> String

emptyPhonebook :: Phonebook
emptyPhonebook _ = ""

insert :: String -> String -> Phonebook -> Phonebook
insert name number phonebook = 
        case phonebook name of 
             "" -> (\s -> if s == name then number else phonebook s)
             _ -> phonebook
查看更多
登录 后发表回答