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.
elem :: element -> list -> Bool. Use elem if you want to check whether a given element exists within a list.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With