on one hand, it would be nice if Haskell had syntactic sugar like "DECONSTRUCT Constructor" which had the meaning
\x -> case x of { Constructor y -> y }
. then, we could avoid having to manually create deconstruction (unwrapping) functions, as commonly manually done with field labels:
newtype Mytype = Constructor { unConstructor :: Innertype }
. in the above example, we are having to repeat ourselves in "Constructor" then "unConstructor", violating the programming mantra Don't Repeat Yourself. (often Mytype == Constructor , another form of repetition, but avoiding that is an issue for another day.)
on the other hand, using the LambdaCase LANGUAGE pragma, the DECONSTRUCT lambda function above can be written fairly succinctly without needing any additional syntactic sugar:
\case{Constructor y->y}
. this lambda can then be used, for example, in function pipelines joined by ($), (.), (Data.Function.&), or (Control.Category.>>>). There remains a little bit of Repeating Yourself in the pattern match variable y.
lenses also achieve wrapping and unwrapping, often using Template Haskell to avoid Repeating Yourself.
1 comment :
For newtypes like your examples, there's also `coerce`.
Post a Comment