John Doe
John Doe

Reputation: 63

Return a function with signature String -> String from another function

I'm programming in Haskell and have the following type.

type Phonebook = String -> String

Now I have to create a function that returns an empty Phonebook, so

emptyPhonebook :: Phonebook
emptyPhonebook = ???

But what is an empty Phonebook?

I mean it has to be an "empty" function, but how do I write that in Haskell?

Upvotes: 0

Views: 362

Answers (2)

There is no such thing as an empty function.

The question is, what should your phonebook return for names that aren't in the phone book?
If this is a learning exercise, you could just return an empty string - as in the other answer.

However, a better definition of your phonebook would be:

type Phonebook = String -> Maybe String

Then your function becomes:

emptyPhoneBook :: Phonebook
emptyPhoneBook _ = Nothing

This is like using nullable types in languages like C#; the Maybe says that your value can either be a String, or Nothing.

For completeness, I should add that if Maybe String contains a string value, its value will be preceded by the keyword Just.
For example, if the String in question was "Judie", the value would be Just "Judie" rather than merely "Judie".
The Just is because the value is of type Maybe String, not of type String.

Upvotes: 7

Netwave
Netwave

Reputation: 42716

I does not have to be an empty funtion, it has to be a String->String function, even id would do

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

Take a look at this running example:

Upvotes: 1

Related Questions