How to delete a template when writing overloaded lines?

Given the following code:

{-# LANGUAGE OverloadedStrings #-} newtype Firstname = Firstname String deriving (Eq, Show) instance IsString Firstname where fromString = Firstname newtype Lastname = Lastname String deriving (Eq, Show) instance IsString Lastname where fromString = Lastname data Person = Person { firstname :: Firstname, lastname :: Lastname, age :: Int } deriving Show 

I would like to remove the template to create strongly typed strings. Is it possible to use Template Haskell (or some other means) to achieve this?

for example, something like:

 {-# LANGUAGE OverloadedStrings, TemplateHaskell #-} $(strongString ''Firstname) $(strongString ''Lastname) data Person = Person { firstname :: Firstname, lastname :: Lastname, age :: Int } deriving Show 
+7
source share
1 answer

Use GeneralizedNewtypeDeriving and print an instance of IsString for Firstname and Lastname . Sample code for your example follows

 {-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving #-} import Data.String newtype Firstname = Firstname String deriving (Eq, Show, IsString) newtype Lastname = Lastname String deriving (Eq, Show, IsString) data Person = Person { firstname :: Firstname , lastname :: Lastname , age :: Int } foo = Person "hello" "world" 10 

You can use TH to write a similar function that you want, but it’s not worth the effort by storing these functions in a separate module and then importing them here.

+14
source

All Articles