Using coerce in Haskell
I recently worked on adding CSRF checks to a form.
module Csrf (
Token
, ...
) where
newtype Token = MkToken String
deriving (Eq, Show)
mkTokens :: [String] -> [Token]
mkTokens = map MkToken
-- ... rest of code
While newtype
comes with no run-time costs, we do encounter some costs if we dealt with converting a list of strings to tokens. I chanced upon Safe Zero-cost Coercions for Haskell, which describes safe coercions for removing this overhead.
mkTokens :: [String] -> [Token]
mkTokens = coerce
See: Coercible