Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

function - Haskell Phonebook adding elements

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 = (
ame->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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...