I have a function defined as follow:
errorWhenNothing :: Maybe a -> M (Maybe a) -- M is a Monad
errorWhenNothing Nothing = throwError "is Nothing!"
errorWhenNothing m = return m
The parameter m
seems trivial and removing it makes the function simpler and more compact. The problem is that I cannot rewrite the second definition as
errorWhenNothing = return
GHC complains Equations for 'errorWhenNothing' have different numbers of arguments..
I want to know is there a way to remove the m
?
答案 0 :(得分:7)
Yeah you can't have different numbers of arguments for different clauses of the same function. It's mostly to catch the common error of leaving out a parameter on one of the lines, so instead of a confusing type error it just tells you what you did wrong straight away.
If you don't want the m
there, you could make the wholething pointfree with the maybe
eliminator
errorWhenNothing :: Maybe a -> M a
errorWhenNothing = maybe (throwError "isNothing!") return
whether this is an improvement is a matter of opinion.
答案 1 :(得分:6)
Why return a Maybe
from errorWhenNothing
? If the input were Nothing
, the computation would have been aborted with a throwError
anyway. Having to pattern-match on the result of the function seems like needless work, because we know at that point that it is not Nothing
.
Perhaps we could rewrite the function like this:
errorWhenNothing :: Maybe a -> M a
errorWhenNothing Nothing = throwError "is Nothing!"
errorWhenNothing (Just a) = return a
Now the second clause doesn't pass the parameter unchanged.