Max
Max

Reputation: 691

Haskell convention: Maybe or empty list?

Could any Haskell experts out there please clarify something for me:

Given a simplified example of a function match which is supposed to return a matched value from a list, which is the "better" function definition to use Maybe or return [] (an empty list)?

That is:

match :: String -> [String] -> Maybe String

or

match :: String -> [String] -> [String]     {- possibly empty, if no match -}

I prefer the first version for reasons of clarity, but I would be interested to know whether there is a convention for this sort of thing.

Upvotes: 6

Views: 1458

Answers (3)

ltc
ltc

Reputation: 3361

I like to use Maybe String. I think it is much more clear. If you think about what you are communicating with the other option, you are saying that your function takes a list and returns either a String or a list upon failure. Semantically that is kind of funky IMO when compared with returning either a String or Nothing.

Upvotes: 2

Itkovian
Itkovian

Reputation: 95

In this case you state that you return a single matched value if it is present. I would go with the Maybe String, otherwise you would return a list containing a single element, which seems to be odd.

Upvotes: 0

luqui
luqui

Reputation: 60503

If it is only ever possible for it to return zero or one matches, then use Maybe (because that's what it means); if it is possible to return any number of matches, then use [] (because that's what it means).

Upvotes: 21

Related Questions