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

 
0
Kudos
 
0
Kudos

Now read this

Having some fun (and pain) with generics

Decided to try and wrap my head around generic programming and ended up sinking too much time trying to understand (or not?) some of the basic ideas. Just for fun, I tried to think how it would be possible to go from a homogenous list... Continue →