Newtypes for replace
cryogenian opened this issue · 8 comments
The errors with replace where I mix up arguments occur surprisingly often.
What do you think, is it worth to add newtype wrappers for replacer/replacee part?
And in general something like Hay and Needle, SplitBy and other stuff?
Since these strings aren't typically going to be placed in data structures, maybe type is enough to make the documentation clear?
Isn't that the suggestion though? Requiring newtype wrapping to ensure the strings must be specified in the right order: replace (Needle x) y (Hay z).
I generally like newtype for this sort of thing, I just think it might be overkill in this case. A type synonym would show up in documentation and editor hints, which would be enough for me. This seems a bit different from something like EmailAddress vs PhoneNumber.
Yeah, but this isn't for documentation purposes, but to remove weird errors and make declarations a bit clearer. And even with assumption that everyone uses right tooling (that's not true of course) editor hints are just recommendations not enfocements.
Other approach is something like
find :: {hay :: String, needle :: String} -> Maybe String It doesn't introduce new types, but currying is lost.
Well except records 😄
type aliases would definitely be an improvement over replace :: String -> String -> String -> String.
However, I have to say I like the newtype approach (I'm not particularly keen about Needle and Hay). I think the overhead is managable, because typically you only need to wrap (and there is no unwrapping involved):
newtype Pattern = Pattern String
newtype Replacement = Replacement String
replace :: Pattern -> Replacement -> String -> String
replace (Pattern "http") (Replacement "https") "http://example.com"If we were to newtype, I prefer @sharkdp's suggestion too - newtyping the first arguments and leaving the last one as a string.
Agreed, that makes composition nicer too.
The other question is whether this is worth a breaking change again, when we haven't finished the 1.0 update cycle yet. (That's part of the reason I suggested using type synonyms to start off with).