Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell convention: Maybe or empty list?

Tags:

haskell

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.

like image 837
Max Avatar asked Mar 26 '11 21:03

Max


People also ask

How do you check if something is in a list Haskell?

elem :: element -> list -> Bool. Use elem if you want to check whether a given element exists within a list.

Is Haskell null?

Haskell does not have "null". This is a design feature. It completely prevents any possibility of your code crashing due to a null-pointer exception.


2 Answers

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).

like image 178
luqui Avatar answered Sep 26 '22 22:09

luqui


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.

like image 41
ltc Avatar answered Sep 25 '22 22:09

ltc