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 -> [Stri开发者_开发知识库ng] -> 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.
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).
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
.
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.
精彩评论